我看到一种方法用 @Value("${some.property}")
如
@Value("${some.property}")
public void setSomething(String param) {
... do something with param
}
那个注释在那里做什么?
最佳答案
基本上它告诉 Spring 的 AutowiredAnnotationBeanPostProcessor以 some.property
的解析值作为参数调用 setSomething
方法...但前提是您有 PropertySourcesPlaceholderConfigurer在你的 bean 定义中;如果您还没有配置一个,后处理器只会将字符串 "${some.property}"
(不带引号)注入(inject)到您的方法中。
如果无法解析该值,则将引发 IllegalArgumentException,除非您使用了默认值,例如"${some.property:default}"
.
Spring 使用当前的 Environment 解析这些值。及其PropertySources例如JVM系统属性、Java属性文件等
您也可以use Spring Expression Language ( SpEL ) 解决诸如 #{someBean.someMethod}
或 #{systemProperties[user.region]}
旁注:如文档所述
Fields are injected right after construction of a bean, before any config methods are invoked. [...] Bean property setter methods [as in this case] are effectively just a special case of such a general config method.
一个常见的错误是尝试使用注入(inject)的值在构造函数中执行一些逻辑,但此时该值尚未解析或注入(inject),因为构造函数必须完成才能在 config 方法中注入(inject)值。在这些情况下,您必须在构造函数参数中使用 @Value
或 @Autowired
注释。
您也可以使用 @PostConstruct
或 XML init-method
属性指向将在设置 bean 属性后执行的方法。或者,您可以实现 InitializingBean界面。
关于spring - 方法中的@Value 注解有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21769445/