using Spring JdbcTemplate - injecting datasource vs jdbcTemplate using Spring JdbcTemplate - injecting datasource vs jdbcTemplate java java

using Spring JdbcTemplate - injecting datasource vs jdbcTemplate


You can do what you want. The javadoc of JdbcTemplate even clearly says it:

Can be used within a service implementation via direct instantiation with a DataSource reference, or get prepared in an application context and given to services as bean reference.


In the spring-context.xml add the following and

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">    <property name="dataSource" ref="dataSource"/></bean>

and directly you can use jdbcTemplate by autowiring like

  @Autowired JdbcTemplate jdbcTemplate;

example:

this.jdbcTemplate.query("select * from ******",new RowMapper());


You can also do it like

@Configuration@Import({PersistenceConfig.class})@ComponentScan(basePackageClasses = {     ServiceMarker.class,    RepositoryMarker.class })public class AppConfig {    /**     * To resolve ${} in @Values, you must register a static PropertySourcesPlaceholderConfigurer in either XML or      * annotation configuration file.     */    @Bean    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {        return new PropertySourcesPlaceholderConfigurer();    }}

PersistenceConfig

@Configuration@PropertySource(value = { "classpath:database/jdbc.properties" })@EnableTransactionManagementpublic class PersistenceConfig {    @Autowired    private Environment env; /**  * The @Bean annotation is used to declare a Spring bean and the DI requirements. The @Bean annotation is equivalent to *  the <bean> tag, the method name is equivalent to the id attribute within the <bean> tag.  *   * <bean id="mySqlDataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"         p:driverClassName="${jdbc.mysql.driverClassName}"         p:url="${jdbc.mysql.url}"           p:username="${jdbc.mysql.username}"         p:password="${jdbc.mysql.password}" />  *   * @return  */     @Bean(destroyMethod = "close")     public DataSource mySqlDataSource() {         BasicDataSource dataSource = new BasicDataSource();         dataSource.setDriverClassName(env.getProperty("jdbc.mysql.driverClassName"));         dataSource.setUrl(env.getProperty("jdbc.mysql.url"));         dataSource.setUsername(env.getProperty("jdbc.mysql.username"));         dataSource.setPassword(env.getProperty("jdbc.mysql.password"));         return dataSource;     }     @Bean(destroyMethod = "close")     public DataSource ls360DataSource() {         BasicDataSource dataSource = new BasicDataSource();         dataSource.setDriverClassName(env.getProperty("jdbc.ls360.driverClassName"));         dataSource.setUrl(env.getProperty("jdbc.ls360.url"));         dataSource.setUsername(env.getProperty("jdbc.ls360.username"));         dataSource.setPassword(env.getProperty("jdbc.ls360.password"));         return dataSource;     } }

MySqlDaoImpl

@Repositorypublic class MySqlDaoImpl implements MySqlDao{    private static final Logger logger = LogManager.getLogger();    @Inject    private DataSource mySqlDataSource;    private JdbcTemplate mySqlJdbcTemplate;    @PostConstruct    public void afterPropertiesSet() throws Exception {        if (mySqlDataSource == null) {            throw new BeanCreationException("Must set mySqlDataSource on " + this.getClass().getName());        }        this.mySqlJdbcTemplate = new JdbcTemplate(mySqlDataSource);    }    @Override    public void callStoredProcedure(String storedProcedureName, Map<String, Object> inParamMap) throws Exception {        SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(mySqlJdbcTemplate).withProcedureName(storedProcedureName);        SqlParameterSource in = new MapSqlParameterSource(inParamMap);        logger.info("Calling stored Procedure: " + storedProcedureName);        Map<String, Object> simpleJdbcCallResult = simpleJdbcCall.execute(in);        logger.info("Stored Procedure Result: " + simpleJdbcCallResult);    }}

Main

public static void main(String[] args ) {    try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {        MySQLDao mySqlDao = springContext.getBean(MySQLDaoImpl.class);        try {            Map<String, Object> inParamMap = new HashMap<String, Object>();            inParamMap.put("iCourseId", 1);            mySqlCourseRenewalDao.callStoredProcedure("usp_processCourseRenewal", inParamMap);        } catch (Exception e) {            logger.error("Exception occurs", e);        }    } catch (Exception e) {        logger.error("Exception occurs in loading Spring context: ", e);    }}

Thanks