0

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;
    }
}

and I have a UserDaoTest and at first I only want just to test it without load other components

@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 {}

When execute test I got below error

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

but if changes UserDaoTest to

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

it's ok.

So why in case one it does not resolve spring.datasource.test-while-idle properly and how could solve it?

zhuguowei
  • 8,401
  • 16
  • 70
  • 106

1 Answers1

0

You also need to import the applicaton.properties or application.yml file that holds that property.

ndrone
  • 3,524
  • 2
  • 23
  • 37