Spring 注释:为什么当 class 是 @Autowired 时 @Required 不起作用

Spring Annotations: Why @Required doesn't work when class is @Autowired

当我有一个class如下:

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 上下文中初始化 Trainer,如下所示:

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

出于某种原因,@Required 注释不适用,上下文启动时没有问题(它应该抛出一个异常,说明字段阈值是必需的...)。

这是为什么?

我认为您可能错过了配置。

Simply applying the @Required annotation will not enforce the property checking, you also need to register an RequiredAnnotationBeanPostProcessor to aware of the @Required annotation in bean configuration file.

可以通过两种方式启用 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. 包括RequiredAnnotationBeanPostProcessor

    直接在 bean 配置文件中包含‘RequiredAnnotationBeanPostProcessor’。

<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"/>