在测试Spring的事务的时候需要连接数据库,但是发现@Value的值一直就是“{${jdbc.url}}”,并没有从配置文件中获取到值,
配置文件的代码如下:
@Configuration
@ComponentScan(basePackages = {"com.huanghe.*"})
@PropertySource("classpath:jdbc.properties")
public class configuration {
@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.driverClassName}")
private String driverClassName;
/**
* 配置数据源
* @return
* @throws PropertyVetoException
*/
@Bean
public ComboPooledDataSource dataSources() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driverClassName);
dataSource.setUser(username);
dataSource.setPassword(password);
dataSource.setJdbcUrl(jdbcUrl);
return dataSource;
}
/**
* 配置JDBCTemplate
* @return
* @throws PropertyVetoException
*/
@Bean
public JdbcTemplate jdbcTemplate() throws PropertyVetoException {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSources());
return jdbcTemplate;
}
/**
* 配置事物管理器
* @return
* @throws PropertyVetoException
*/
@Bean
public DataSourceTransactionManager dataSourceTransactionManager() throws PropertyVetoException {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSources());
return dataSourceTransactionManager;
}
@Bean
public Person person(){
return new Person("huanghe");
}
}
测试代码:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = configuration.class)
public class TestAppAnnonation {
@Autowired
private AccountService accountService;
@Test
public void test() {
accountService.transfer("jack", "rose", 1000);
}
}
在运行的时候会报出Could not load driverClass ${jdbc.driverClassName}
异常,也就是说driverClassName的值没有获取到。
解决:
在配置文件中加入:
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
加入之后就能完整的运行成功了