1. 程式人生 > >Spring問題集:@value放在Spring基於java的配置檔案中取不到值

Spring問題集:@value放在Spring基於java的配置檔案中取不到值

在測試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();
    }

加入之後就能完整的執行成功了