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

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

问题描述

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

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

该注释在那里做什么?

推荐答案

基本上,它告诉Spring的PropertySourcesPlaceholderConfigurer ;如果您尚未配置,则后处理器只会将字符串"${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 )来解决#{systemProperties[user.region]}

边注:如文档所述

字段是在构造bean之后立即注入的, config方法被调用. [...] Bean属性设置器方法(在这种情况下)实际上只是这种常规config方法的特例.

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天全站免登陆