Java 为什么@ConfigurationProperties类的默认值不起作用?
我的Spring Boot应用程序中有一个类用于: 稍后,我尝试将其用于带有注释的bean中的字段:Java 为什么@ConfigurationProperties类的默认值不起作用?,java,spring,spring-boot,Java,Spring,Spring Boot,我的Spring Boot应用程序中有一个类用于: 稍后,我尝试将其用于带有注释的bean中的字段:@Value(${props.param1}”) 但在应用程序启动时,我会遇到以下异常,直到我在application.properties 原因:java.lang.IllegalArgumentException:无法解析 字符串值“${props.param1}”中的占位符“props.param1” 如何使Spring Boot应用程序使用默认值而不在application.propert
@Value(${props.param1}”)
但在应用程序启动时,我会遇到以下异常,直到我在application.properties
原因:java.lang.IllegalArgumentException:无法解析
字符串值“${props.param1}”中的占位符“props.param1”
如何使Spring Boot应用程序使用默认值而不在application.properties
中指定值
当我在application.properties
中键入属性时,我在IDE中看到了默认值,并且在生成的spring配置元数据.json
文件中有一个defaultValue
。我想这个默认值应该与spring一起使用,直到我在我的属性文件中对它进行了验证,但是由于未知的原因,我从上面得到了异常
稍后,我尝试在带注释的bean中的字段上使用它:
@Value(${props.param1}”)
这种所谓的类型安全配置是处理属性的另一种方法,它允许强类型bean管理和验证应用程序的配置
引入ConfigurationProperties
的目的就是不要使用繁琐且容易出错的@Value
s。您不应使用@Value
,而应使用@Autowired
插入属性
配置:
@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
,请先删除属性
类,然后使用@Value(${key:defaultValue}”)
符号,如下所示:
@Value("${props.param1:val1}")
稍后,我尝试在带注释的bean中的字段上使用它:
@Value(${props.param1}”)
这种所谓的类型安全配置是处理属性的另一种方法,它允许强类型bean管理和验证应用程序的配置
引入ConfigurationProperties
的目的就是不要使用繁琐且容易出错的@Value
s。您不应使用@Value
,而应使用@Autowired
插入属性
配置:
@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
,请先删除属性
类,然后使用@Value(${key:defaultValue}”)
符号,如下所示:
@Value("${props.param1:val1}")
您究竟是如何使用
属性组件的?使用@Value
或@Autowired
?@AliDehghani我提到过,我使用了@Value)@AliDehghani我试图设置它,但没有在我的主类上设置它-没有区别您到底是如何使用属性
组件的?使用@Value
或@Autowired
?@AliDehghani我提到过,我使用了@Value)@AliDehghani我试图设置它,而不是在我的主类上设置它-没有什么区别,就像我对类型安全属性的错误想象一样。谢谢你的解释。我应该在哪里使用配置类的getter?根据文档,我可以使用@PostConstruct
方法。如果您指的是getParam1
,getParam2
等,那么您可以在任何Spring管理的bean中使用它们(@Repository
,@Component
,@Service
,@Configuration
)。Spring Boot本身经常使用这些配置属性,例如,您可以查看我在该链接上看到的@EnableConfigurationProperties注释,但不了解它是如何被家长使用的,不需要使用@EnableConfigurationProperties
。看这里,看起来我对类型安全属性的想象是错误的。谢谢你的解释。我应该在哪里使用配置类的getter?根据文档,我可以使用@PostConstruct
方法。如果您指的是getParam1
,getParam2
等,那么您可以在任何Spring管理的bean中使用它们(@Repository
,@Component
,@Service
,@Configuration
)。Spring Boot本身经常使用这些配置属性,例如,您可以查看我在该链接上看到的@EnableConfigurationProperties注释,但不了解它是如何被家长使用的,不需要使用@EnableConfigurationProperties
。看这里