1. DatasourceCreateDemo.java
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
public class DatasourceCreateDemo {
public static void main(String[] args){
new Tester().testJdbcTemplate();
}
}
class DataSourceFactory {
public DataSource createDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("driver.class.name");
dataSource.setUrl("sqlurl");
dataSource.setUsername("username");
dataSource.setPassword("password");
return dataSource;
}
}
class Tester{
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public void testJdbcTemplate(){
System.out.println(jdbcTemplateObject==null);
}
}
2. spring config
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id = "dataSourceFactory" class = "xxx.xxx.DataSourceFactory" />
<bean id = "dataSource" factory-bean = "dataSourceFactory" factory-method = "createDataSource" />
<bean id="Tester"
class="xxx.xxx.Tester">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>