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

Kir*_*ill 0 java spring spring-boot

我的Spring Boot应用程序中有一个类用于类型安全配置:

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

后来我尝试在带有注释的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,直到我在我的属性文件中进行操作,但由于未知原因,我从上面得到了例外.

Ali*_*ani 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
}
Run Code Online (Sandbox Code Playgroud)

如果您坚持使用@Value,请首先删除Properties该类,然后使用@Value("${key:defaultValue}")如下符号:

@Value("${props.param1:val1}")
Run Code Online (Sandbox Code Playgroud)