In Spring Boot I attempt to inject a boolean value to an instance variable from an enviroment property which is set (enabled=true
).
@Value("${enabled}")
private boolean enabled;
However Spring cannot resolve this for some reason and reports:
Caused by: java.lang.IllegalArgumentException: Invalid boolean value [${enabled}]
It seems like it does not replace expression ${enabled}
with the property value.
What needs to be set ? Why doesn't work this by default ?
For Spring-Boot you can find good reference here: http://www.baeldung.com/properties-with-spring
For given someprops.properites file:
somevalue:true
Here is FAILING version:
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource( "/someprops.properties" )
public class FailingNg {
@Configuration
public static class Config {
}
@Value("${somevalue}")
private Boolean somevalue;
// Fails with context initializatoin java.lang.IllegalArgumentException: Invalid boolean value [${somevalue}]
@Test
public void test1() {
System.out.println("somevalue: " + somevalue);
}
}
Here is WORKING version:
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class WorkingOk {
@Configuration
public static class Config {
@Bean
public static PropertyPlaceholderConfigurer properties() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[] {
new ClassPathResource( "someprops.properties" )
};
ppc.setLocations( resources );
ppc.setIgnoreUnresolvablePlaceholders( true );
return ppc;
}
}
@Value("${somevalue}")
private Boolean somevalue;
@Test
public void test1() {
System.out.println("somevalue: " + somevalue);
}
}
As mentioned in the comments, you are likely missing a PropertySourcesPlaceholderConfigurer bean definition. Here's an example of how to configure that within Java:
@Configuration
public class PropertyConfig {
private static final String PROPERTY_FILENAME = "app.properties"; // Change as needed.
/**
* This instance is necessary for Spring to load up the property file and allow access to
* it through the @Value(${propertyName}) annotation. Also note that this bean must be static
* in order to work properly with current Spring behavior.
*/
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[] { new ClassPathResource(PROPERTY_FILENAME) };
pspc.setLocations(resources);
pspc.setIgnoreUnresolvablePlaceholders(true);
return pspc;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With