Search code examples
javaspringautowiredspring-annotations

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:

<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...).

Why is that??


Solution

  • 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.

    The RequiredAnnotationBeanPostProcessor can be enabled in two ways.

    1. Include <context:annotation-config/>

      Add Spring context and in bean configuration file.

      <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

      Include ‘RequiredAnnotationBeanPostProcessor’ directly in bean configuration file.

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