What does the @Value annotation in method do?

2020-08-09 09:45发布

问题:

I see one method annotated with @Value("${some.property}")

as in

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

What is that annotation doing there?

回答1:

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.

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

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

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

Sidenote: As the documentation states

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.

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.

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.