spring - 方法中的@Value 注解有什么作用?

标签 spring annotations

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

注释

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

那个注释在那里做什么?

最佳答案

基本上它告诉 Spring 的 AutowiredAnnotationBeanPostProcessorsome.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/

相关文章:

java - spring roo windows安装 "Could not find or load main class"

swift - 如何从具有多个图钉的 map View 中删除一个图钉

kotlin - Kotlin通过反射读取属性注释

java - 使用注释进行异常处理?

java - HTTP 状态 500 - javax.servlet.ServletException : Servlet execution threw an exception

java - Spring 数据休息 : how to send Multi-part file with request Body

database - Hibernate 在架构更新时自动创建 SQL 迁移脚本以与 Flyway 一起使用

java - Spring ApplicationContext - 资源泄漏 : 'context' is never closed

java - 如何使用junit测试java中的注释

java - 内部源保留注释的表示