Spring bean reference example

In Spring, beans can “access” to each other by specify the bean references in the same or different bean configuration file.

1. Bean in different XML files

If you are referring to a bean in different XML file, you can reference it with a ‘ref‘ tag, ‘bean
‘ attribute.


In this example, the bean “OutputHelper” declared in ‘Spring-Common.xml‘ can access to other beans in ‘Spring-Output.xml‘ – “CsvOutputGenerator” or “JsonOutputGenerator“, by using a ‘ref’ attribute in property tag.

File : Spring-Common.xml



    
        
            
        
    

File : Spring-Output.xml



    
    

2. Bean in same XML file

If you are referring to a bean in same XML file, you can reference it with ‘ref‘ tag, ‘local‘ attribute.


In this example, the bean “OutputHelper” declared in ‘Spring-Common.xml‘ can access to each other “CsvOutputGenerator” or “JsonOutputGenerator“.

File : Spring-Common.xml



    
        
            
        
    
    
    

Conclusion

Actually, the ‘ref’ tag can access to a bean either in same or different XML files, however, for the project readability, you should use the ‘local’ attribute if you reference to a bean which declared in the same XML file.

你可能感兴趣的:(Spring bean reference example)