为什么spring boot test无法识别属性值?

时间:2017-06-27 06:54:22

标签: spring-boot spring-boot-test

spring boot + jdbctemplate

@Configuration
public class MultiDBConfig implements BeanPostProcessor{

    @Value("${spring.datasource.test-while-idle}")
    private boolean  testWhileIdle;
    //...
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof org.apache.tomcat.jdbc.pool.DataSource){
            org.apache.tomcat.jdbc.pool.DataSource ds = (org.apache.tomcat.jdbc.pool.DataSource) bean;
            ds.setTestWhileIdle(testWhileIdle);

        }
        return bean;
    }
}

我有一个UserDaoTest,起初我只想测试它而不加载其他组件

@RunWith(SpringRunner.class)
@JdbcTest(includeFilters = @ComponentScan.Filter(type= FilterType.ASSIGNABLE_TYPE,value=UserDao.class))
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
@Import(MultiDBConfig.class)
public class UserDaoTest {}

执行测试时我得到以下错误

Caused by: java.lang.IllegalArgumentException: Invalid boolean value [${spring.datasource.test-while-idle}]
    at org.springframework.beans.propertyeditors.CustomBooleanEditor.setAsText(CustomBooleanEditor.java:123)

但是如果将UserDaoTest更改为

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserDaoTest {...}

没关系。

那么为什么如果一个它没有正确解决spring.datasource.test-while-idle以及如何解决它?

1 个答案:

答案 0 :(得分:0)

您还需要导入包含该属性的applicaton.propertiesapplication.yml文件。