IllegalArgumentException:在Spring中将属性注入boolean时的布尔值无效

时间:2015-09-30 13:59:26

标签: java spring spring-boot

在Spring Boot中,我尝试从设置(enabled=true)的环境属性中为实例变量注入一个布尔值。

@Value("${enabled}")
private boolean enabled;

然而Spring出于某种原因无法解决这个问题并报道:

Caused by: java.lang.IllegalArgumentException: Invalid boolean value [${enabled}]

似乎它不会将表达式${enabled}替换为属性值。

需要设置什么?为什么默认情况下不会这样做?

2 个答案:

答案 0 :(得分:1)

对于Spring-Boot,您可以在这里找到很好的参考资料: http://www.baeldung.com/properties-with-spring

对于给定的 someprops.properites 文件:

node {
  stage('CLONE') {

          dir('MVD') {
            git url: 'ssh://git@git.rocketsoftware.com:7999/lg6/mvd.git',
                credentialsId: 'Jenkins_MVD_SSHKEY',
                branch: 'feature/MVD-1809-1810'
          }


          dir('MVDZOS') {   
            git url: 'ssh://git@git.rocketsoftware.com:7999/lg6/mvdzos.git',
                credentialsId: 'Jenkins_MVD_SSHKEY',
                branch: 'master'

          }
          def ws = pwd()/MVDZOS
          sh 'ls ${ws}'

          sh 'ls ${workspace}'
          sh 'ls -la MVD'
          sh 'ls -la MVDZOS'
          sh 'cd MVD/utils && python compareWhitelist.py "${MVDZOS}"'

  }
}

这是失败版本:

somevalue:true

这是工作版本:

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

答案 1 :(得分:0)

如评论中所述,您可能缺少PropertySourcesPlaceholderConfigurer bean定义。以下是如何在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;
    }
}