Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use <ref bean> and when to use <ref local> in Spring?

Tags:

spring

When to use <ref bean="service" /> and when to use <ref local="service" /> in Spring?

like image 701
Jyotirup Avatar asked Jan 05 '12 09:01

Jyotirup


People also ask

What is Ref local in Spring?

ref local requires that the bean being referenced is in the same config file. Ref bean requires only it to be in the same context or in the parent context.

What is ref bean in Spring?

In Spring we need to use <ref> element to inform spring container about the object dependency. In Spring, beans can "access" to each other by specify the bean references in the same or different bean configuration file.In spring we can write multiple configuration xml file.

How do I reference a bean of another XML file in Spring?

Just import the xml defining the bean with <import resource="otherXml. xml"> and you will be able to use the bean definition.


2 Answers

Specifying the target bean by using the bean attribute of the ref tag is the most general form, and will allow creating a reference to any bean in the same BeanFactory/ApplicationContext (whether or not in the same XML file), or parent BeanFactory/ApplicationContext. The value of the bean attribute may be the same as either the id attribute of the target bean, or one of the values in the name attribute of the target bean.

<ref bean="someBean"/> 

Specifying the target bean by using the local attribute leverages the ability of the XML parser to validate XML id references within the same file. The value of the local attribute must be the same as the id attribute of the target bean. The XML parser will issue an error if no matching element is found in the same file. As such, using the local variant is the best choice (in order to know about errors are early as possible) if the target bean is in the same XML file.

<ref local="someBean"/> 

This is from the Spring source reference here

like image 130
Aravind A Avatar answered Sep 20 '22 13:09

Aravind A


The local attribute on the ref element is no longer supported in the 4.0 beans xsd since it does not provide value over a regular bean reference anymore. Simply change your existing ref local references to ref bean when upgrading to the 4.0 schema.

like image 30
Vinod Cyriac Avatar answered Sep 21 '22 13:09

Vinod Cyriac