IllegalArgumentException: Invalid boolean value when injecting property to boolean in Spring

13,133

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);
    }
}
Share:
13,133

Related videos on Youtube

ps-aux
Author by

ps-aux

Updated on September 15, 2022

Comments

  • ps-aux
    ps-aux over 1 year

    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 ?