方法中的@Value 注释有什么作用? [英] What does the @Value annotation in method do?

查看:32
本文介绍了方法中的@Value 注释有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一种用 @Value("${some.property}")

@Value("${some.property}")
public void setSomething(String param) {
    ... do something with param
}

那个注释在那里做什么?

What is that annotation doing there?

推荐答案

基本上它告诉 Spring 的 AutowiredAnnotationBeanPostProcessorsome.property的解析值作为参数调用setSomething方法... 但前提是你有一个 PropertySourcesPlaceholderConfigurer 在你的 bean 定义中;如果您还没有配置,后处理器只会将字符串 "${some.property}"(不带引号)注入到您的方法中.

Basically it tells Spring's AutowiredAnnotationBeanPostProcessor to call the setSomething method with the resolved value of some.property as the argument... but only if you have a PropertySourcesPlaceholderConfigurer in your bean definitions; if you haven't configured one the post processor will only inject the string "${some.property}"(without quotes) to your method.

如果值无法解析,除非您使用了默认值,否则将抛出 IllegalArgumentException 异常,例如"${some.property:default}".

An IllegalArgumentException will be thrown if the value could not be resolved unless you have used a default e.g. "${some.property:default}".

Spring 使用当前的 解析这些值环境及其PropertySources 例如JVM 系统属性、Java 属性文件等.

Spring resolves these values using the current Environment and its PropertySources e.g. JVM system properties, a Java properties file, etc.

您也可以使用 Spring 表达式语言 (SpEL) 来解决诸如 #{someBean.someMethod}#{systemProperties[user.region]}

Also you may use Spring Expression Language (SpEL) to resolve things like #{someBean.someMethod} or #{systemProperties[user.region]}

旁注:如文档所述

在构建 bean 之后立即注入字段,然后再注入任何字段配置方法被调用.[...] Bean 属性 setter 方法 [如本例所示] 实际上只是这种通用配置方法的一个特例.

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.

一个常见的错误是尝试使用注入的值在构造函数中执行某些逻辑,但此时该值尚未解析或注入,因为构造函数必须完成才能在 config 方法中注入值.在这些情况下,您必须在构造函数参数中使用 @Value@Autowired 注释.

A common mistake is to try to execute some logic in your constructor using the value injected but at this moment the value has not be resolved nor injected because the constructor must finish in order to inject the value in the config method. In these cases you have to use the @Value or @Autowired annotations in your constructor arguments.

您还可以使用 @PostConstruct 或 XML init-method 属性指向将在设置 bean 属性后执行的方法.或者,您可以实现 InitializingBean界面.

You may also use @PostConstruct or the XML init-method attribute pointing to a method that will be executed after the bean properties have been set. Alternatively you can implement the InitializingBean interface.

这篇关于方法中的@Value 注释有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆