java - 为什么@Value 作为构造函数的参数正确填充属性?

标签 java spring spring-boot

我的问题是:为什么这段代码正确设置了构造函数参数属性port :

private final RedisServer redisServer;

public RedisTestConfiguration(@Value("${cache.port}") final int port) {
   this.redisServer = new RedisServer(port);
}

据我了解,@Value("${cache.port}")由名为 AutowiredAnnotationBeanPostProcessor 的 BeanPostProcessor 解析。 Spring bean 生命周期的工作方式是在任何 BeanPostProcess 之前调用构造函数方法,请参见下图。注意构造函数在 BeanPostProcessor.postProcessBeforeInitialization() 之前被调用。

Spring Bean life cycle

这怎么还在工作?

问候,

巴特

最佳答案

PropertySourcesPlaceholderConfigurer 支持此行为

引用:https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-placeholderconfigurer

PropertySourcesPlaceholderConfigurer 是一个 BeanFactoryPostProcessor。它收集 @Value 字段并更新 spring 容器中的 bean 定义。 PropertySourcesPlaceholderConfigurer 应该在初始化任何 bean 之前在容器中创建。

文档中描述了 Bean 元数据:
https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-metadata

因此,流程如下:
1. Bean 定义阅读器从 xml 文件或 java 类中收集 bean 声明。例如,XmlBeanDefinitionReader。

引用:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/xml/XmlBeanDefinitionReader.html

  • Bean Factory 后处理器更新 bean 定义。例如,PropertySourcesPlaceholderConfigurer。
  • Spring 容器查看 bean 定义并根据 bean 定义值创建 bean(调用构造函数)。
    引用:https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-class

  • 所以,问题是As of my understanding, @Value("${cache.port}") is resolved by a BeanPostProcessor是不正确的。 @Value 由 BeanFactoryPostProcessor 管理,而不是 BeanPostProcessor

    实际上,文档指出:
    A default lenient embedded value resolver is provided by Spring. It will try to resolve the property value and if it cannot be resolved, the property name (for example ${catalog.name}) will be injected as the value. If you want to maintain strict control over nonexistent values, you should declare a PropertySourcesPlaceholderConfigurer bean, as the following example shows:...
    Spring 有某种默认属性解析器,即另一个 BeanFactoryPostProcessor。但是可以使用 PropertySourcesPlaceholderConfigurer 覆盖它

    关于java - 为什么@Value 作为构造函数的参数正确填充属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61406578/

    相关文章:

    java - spring boot jdbc 连接

    java - 如何获得无序的键值对

    java - Android for 循环中的 “Only the original thread that created a view hierarchy can touch its views.” 错误

    java - Primefaces 树表 : Deleting node using p:ajax not work

    java - 如何防止 Spring 中所有的 Jackson 自动配置?

    java - 在STS中使用带有spring boot的jaxb2 maven插件时收到错误

    java - 在 JavaFx 中创建一个可滚动的 VBox

    java - Spring 在运行 TestNG 测试用例时加载 ApplicationContext 失败 - AutoProxyRegistrar.class 无法打开

    java - Spring MVC WebApp 中的推送通知

    spring - CrudRepository findOne() 和 JpaRepository getOne() 的区别