- 原因:SpringConfigHand是一个配置类,spring容器不会创建SpringConfigHand对象,也就意味着不会对类中的成员变量进行赋值
- 解决方案:将通过@Value注入的数据配置到带@Bean注解的方法里面。
- 原因: spring容器会管理@Bean注解的方法的返回对象.
@Configuration
@ComponentScan("com.hand.service")
@Import(DataSourceConfig.class)
public class SpringConfigHand2 {
@Value("${jdbc.driver}") * String driver;
@Value("${jdbc.url}") String url;
@Value("${jdbc.username}") String username;
@Value("${jdbc.password}") String password;
@Bean
public DataSource getDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUsername(username);
dataSource.setUrl(url);
dataSource.setPassword(password);
return dataSource;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
ssfb.setTypeAliasesPackage("com.hand.entity");
ssfb.setDataSource(dataSource);
return ssfb;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.hand.dao");
return msc;
}
@Bean
public PlatformTransactionManager createTransactionManager(DataSource dataSource){
DataSourceTransactionManager pt = new DataSourceTransactionManager();
pt.setDataSource(dataSource);
return pt;
}
}
- 上述代码存在的问题就是在加载配置类的时候不会对成员变量进行赋值,所以就会出现url not set的错误。事实上,driver、url、username、password都没有set
- 解决办法:将通过@Value注入的数据配置到带@Bean注解的方法里面。即将代码上述代码的成员变量通过参数传递的方式传递给方法。
@Configuration
@ComponentScan("com.hand.service")
@Import(DataSourceConfig.class)
public class SpringConfigHand2 {
@Bean
public DataSource getDataSource(@Value("${jdbc.driver}") String driver,
@Value("${jdbc.url}") String url,
@Value("${jdbc.username}") String username,
@Value("${jdbc.password}") String password){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUsername(username);
dataSource.setUrl(url);
dataSource.setPassword(password);
return dataSource;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
ssfb.setTypeAliasesPackage("com.hand.entity");
ssfb.setDataSource(dataSource);
return ssfb;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.hand.dao");
return msc;
}
@Bean
public PlatformTransactionManager createTransactionManager(DataSource dataSource){
DataSourceTransactionManager pt = new DataSourceTransactionManager();
pt.setDataSource(dataSource);
return pt;
}
}