今天在使用Spring整合Mybatis时,使用配置类代替xml配置,需要读取db.properties中的值来配置数据库连接池,发现不管怎么配置,driver、url等都是null;后来看到一篇博客给出了解决方案和原因,原因因为设计到SpringIOC的源码,现在还不太明白,下面给出解决措施:想知道原理可以参考这篇文章:http://yeming.me/2017/04/16/springValueAnnotation/
- 原来的配置类:
@ComponentScan(basePackages = {"dao", "service"})
@PropertySource("classpath:db.properties")
public class SpringConfig {
@Value("${driver}")
private String driver;
@Value("${url}")
private String url;
@Value("${user}")
private String user;
@Value("${password}")
private String password;
@Bean
public MapperScannerConfigurer createMapperScannerConfigurer() {
MapperScannerConfigurer config = new MapperScannerConfigurer();
config.setBasePackage("dao");
config.setSqlSessionFactoryBeanName("sqlSessionFactory");
return config;
}
@Bean("sqlSessionFactory")
public SqlSessionFactoryBean createSqlSessionFactory(DataSource dataSource) {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean;
}
@Bean("dataSource")
public DataSource createDataSource() throws PropertyVetoException {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(user);
ds.setPassword(password);
return ds;
}
@Bean("transactionManager")
public DataSourceTransactionManager createDataDataSourceTransactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
- 解决措施
(1)在配置类前面加上@Scope(“prototype”):真正开发时并不推荐
(2)拆分配置文件:把数据库相关配置拆分出去:
<1> 把数据库相关配置写到DatabaseConfig.java
@Configuration
@PropertySource("classpath:db.properties")
public class DatabaseConfig {
@Value("${driver}")
private String driver;
@Value("${url}")
private String url;
@Value("${user}")
private String user;
@Value("${password}")
private String password;
@Bean("dataSource")
public DataSource createDataSource() throws PropertyVetoException {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(user);
ds.setPassword(password);
return ds;
}
}
<2>在主配置文件中删去关于数据库的配置,并引入数据库的配置类
@ComponentScan(basePackages = {"dao", "service"})
@Import(DatabaseConfig.class)
public class SpringConfig {
@Bean
public MapperScannerConfigurer createMapperScannerConfigurer() {
MapperScannerConfigurer config = new MapperScannerConfigurer();
config.setBasePackage("dao");
config.setSqlSessionFactoryBeanName("sqlSessionFactory");
return config;
}
@Bean("sqlSessionFactory")
public SqlSessionFactoryBean createSqlSessionFactory(DataSource dataSource) {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean;
}
@Bean("transactionManager")
public DataSourceTransactionManager createDataDataSourceTransactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
大功告成。欸,有时间还是要看一下Spring的源码,要是懂了原理估计早就解决了;做个记录;