Spring dependency checking with @Required Annotation

Spring’s dependency checking in bean configuration file is used to make sure all properties of a certain types (primitive, collection or object) have been set. In most scenarios, you just need to make sure a particular property has been set, but not all properties..
For this case, you need @Required annotation, see following example :

@Required example

A Customer object, apply @Required in setPerson() method to make sure the person property has been set.

package com.mkyong.common;
import org.springframework.beans.factory.annotation.Required;

public class Customer { 
    private Person person; 
    private int type; 
    private String action; 
    public Person getPerson() { 
        return person; 
    } 
   
    @Required 
    public void setPerson(Person person) { 
        this.person = person; 
    }
}

Simply apply 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
    Add Spring context and in bean configuration file.
  
    ... 
     
    ...

Full example,



    
    
        
        
    
    
        
        
        
    

2. Include RequiredAnnotationBeanPostProcessor

Include ‘RequiredAnnotationBeanPostProcessor’ directly in bean configuration file.



    
    
        
        
    
    
        
        
        
    

If you run it , the following error message will be throw, because person property is unset.

org.springframework.beans.factory.BeanInitializationException: Property 'person' is required for bean 'CustomerBean'

Conclusion

Try @Required annotation, it is more flexible than dependency checking in XML file, because it can apply to a particular property only.

你可能感兴趣的:(Spring dependency checking with @Required Annotation)