简体   繁体   English

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

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

When I have a class as follows: 当我有一个课程如下:

public class MyConfig {
    private Integer threshold;

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

And I use it as follows: 我用它如下:

public class Trainer {
    @Autowired
    private MyConfig configuration;

    public void setConfiguration(MyConfig configuration) { this.configuration = configuration; }
}

And initialize the Trainer in the xml context as follows: 并在xml上下文中初始化Trainer,如下所示:

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

For some reason the @Required annotation doesn't apply, and The context starts without a problem (It should have thrown an exception saying the field threshold is required...). 由于某种原因,@ Required注释不适用,并且上下文开始没有问题(它应该抛出一个异常,说明需要字段阈值......)。

Why is that?? 这是为什么??

I think you might have missed a configuration. 我想你可能错过了配置。

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. 简单地应用@Required注释不会强制执行属性检查,您还需要注册RequiredAnnotationBeanPostProcessor以了解bean配置文件中的@Required注释。

The RequiredAnnotationBeanPostProcessor can be enabled in two ways. RequiredAnnotationBeanPostProcessor可以通过两种方式启用。

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

    Add Spring context and in bean configuration file. 添加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. Include RequiredAnnotationBeanPostProcessor 包括RequiredAnnotationBeanPostProcessor

    Include ' RequiredAnnotationBeanPostProcessor ' directly in bean configuration file. 直接在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"/> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM