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

dev*_*ull 5 java spring spring-boot

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

@Value("${enabled}")
private boolean enabled;
Run Code Online (Sandbox Code Playgroud)

但是,由于某种原因,Spring 无法解决此问题并报告:

Caused by: java.lang.IllegalArgumentException: Invalid boolean value [${enabled}]
Run Code Online (Sandbox Code Playgroud)

似乎它没有${enabled}用属性值替换表达式。

需要设置什么?为什么默认情况下不起作用?

小智 1

正如评论中提到的,您可能缺少 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;
    }
}
Run Code Online (Sandbox Code Playgroud)