春季注释:为什么@Required在@Autowired课时不起作用



当我有一个类时,如下所示:

public class MyConfig {
    private Integer threshold;
    @Required
    public void setThreshold(Integer threshold) { this.threshold = threshold; }
}

我按如下方式使用它:

public class Trainer {
    @Autowired
    private MyConfig configuration;
    public void setConfiguration(MyConfig configuration) { this.configuration = configuration; }
}

并在 xml 上下文中初始化训练器,如下所示:

<bean id="myConfiguration" class="com.xxx.config.MyConfig">
        <!--<property name="threshold" value="33"/>-->
</bean>

由于某种原因,@Required注释不适用,并且上下文开始没有问题(它应该抛出一个异常,说字段阈值是必需的......

为什么??

我想你可能错过了一个配置。

仅应用@Required批注不会强制执行属性 检查,您还需要注册一个 需要注释BeanPostProcessor来识别@Required Bean 配置文件中的注释。

RequiredAnnotationBeanPostProcessor可以通过两种方式启用。

  1. 包括<context:annotation-config/>

    添加 Spring 上下文和 Bean 配置文件。

    <beans 
    ...
    xmlns:context="http://www.springframework.org/schema/context"
    ...
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd" >
    ...
    <context:annotation-config />
    ...
    </beans>
    
  2. 包括必需的注释BeanPostProcessor

    将 'RequiredAnnotationBeanPostProcessor' 直接包含在 bean 配置文件中。

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean 
class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>

最新更新