为什么@ConfigurationProperties类的默认值不起作用?

时间:2016-07-01 13:05:20

标签: java spring spring-boot

我在typesafe configuration的Spring Boot应用程序中有一个类:

@Component
@ConfigurationProperties(prefix = "props")
@Getter
@Setter
public class Properties {
    private String param1 = "val1";
    private String param2 = "val2";
}

稍后我尝试在带有注释的bean中的字段上使用它:@Value("${props.param1}")

但是我在应用程序启动时遇到以下异常,直到我在application.properties

中为我的自定义属性指定了值
  

引起:java.lang.IllegalArgumentException:无法解决   占位符' props.param1'在字符串值" $ {props.param1}"

如何使Spring Boot应用程序使用默认值而不指定application.properties中的值?

当我在application.properties中键入属性并且生成的defaultValue文件中有spring-configuration-metadata.json时,我在IDE中看到了默认值。我想这个默认值应该是spring,直到我在我的属性文件中进行处理,但由于未知原因,我从上面得到了例外。

1 个答案:

答案 0 :(得分:6)

  

稍后我尝试在带有注释的bean中的字段上使用它:   @Value("${props.param1}")

这种所谓的 Typesafe配置是一种使用属性的替代方法,允许强类型bean管理和验证应用程序的配置。

引入ConfigurationProperties的重点是不要使用繁琐且容易出错的@Value。您应该使用@Value来注入@Autowired配置,而不是使用Properties

@Service // or any other Spring managed bean
public class SomeService {
    /**
     * After injecting the properties, you can use properties.getParam1()
     * to get the param1 value, which is defaults to val1
     */
    @Autowired private Properties properties; 

    // Other stuff
}

如果您坚持使用@Value,请先删除Properties课程,然后使用@Value("${key:defaultValue}")表示法,如下所示:

@Value("${props.param1:val1}")