How to configure spring datasource programmatically in web based app which uses JdbcTemplate and SpringDaoSupport?

StackOverflow https://stackoverflow.com/questions/23298018

Question

I am trying to create a spring web app which is using JdbcTemplate and SpringDaoSupport. When I am defining the datasource bean through dispatcher-servlet xml it's working fine. i.e.

<bean id="dataSource" 
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
  <property name="url" value="jdbc:oracle:thin:@localhost:1521:XE"/>
  <property name="username" value="system"/>
  <property name="password" value="password1$"/>
</bean>             

But whenever I'm tryinh to configure the dataSource bean through program, it getting exception.The configuration is as follows:

In code:

@Configuration
public class AppConfig {

    @Bean
    public DriverManagerDataSource dataSource() {
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
        driverManagerDataSource.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
        driverManagerDataSource.setUsername("username");
        driverManagerDataSource.setPassword("password");
        return driverManagerDataSource;
    }   
}

In XML:

<bean id="dataSource" class="com.example.AppConfig" />    
Was it helpful?

Solution

In your dispatcher-servlet.xml you need to make sure you have either:

<context:annotation-config/>

<bean class="com.example.AppConfig" />

or

<context:component-scan base-package="com.example"/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top