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.


	<ref bean="someBean"/>

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


<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 id="OutputHelper" class="com.mkyong.output.OutputHelper">
		<property name="outputGenerator" >
			<ref bean="CsvOutputGenerator"/>
		</property>
	</bean>

</beans>

File : Spring-Output.xml


<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 id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator" />
	<bean id="JsonOutputGenerator" class="com.mkyong.output.impl.JsonOutputGenerator" />
		
</beans>

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.


	<ref local="someBean"/>

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

File : Spring-Common.xml


<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 id="OutputHelper" class="com.mkyong.output.OutputHelper">
		<property name="outputGenerator" >
			<ref local="CsvOutputGenerator"/>
		</property>
	</bean>
	
	<bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator" />
	<bean id="JsonOutputGenerator" class="com.mkyong.output.impl.JsonOutputGenerator" />
		
</beans>

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.

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
17 Comment threads
5 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
18 Comment authors
ShivaniMax HollowayYounis Irshadshareefabhimanyu Recent comment authors
newest oldest most voted
Vivek Pandey
Guest
Vivek Pandey

Just FYI,

Please add your Spring-Output.xml in Spring-Common.xml using import Statment

 

<import resource="Spring-Output.xml" />

 

to load this bean configuration file.

sumit sharma
Guest
sumit sharma

Sir,

but its not working using import tag, error become
Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.1: Element ‘import’ must have no character or element information item [children], because the type’s content type is empty.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:384)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(XMLSchemaValidator.java:410)

Please reply.

Max Holloway
Guest
Max Holloway

ref local is not supported anymore after spring 4.0

Shivani
Guest
Shivani

Is idref local not supported as well after spring 4.0?

Younis Irshad
Guest
Younis Irshad

[WORKED] Spring config.xml:

shareef
Guest
shareef

can i ask whats the default if no local key word exists.. ?
and the bean id is redundant in more than one file.?

abhimanyu
Guest
abhimanyu

myyong can you please tell me better way of learning

Alabama Mothman
Guest
Alabama Mothman

Is there any importance to what the bean “id” is? Are there any do’s and do not’s to this?

Er Suraj PandEy
Guest
Er Suraj PandEy

nyc 1 …… Well Done !! This is another good example. Keep posting good stuff.

Marnel Rodriguez
Guest
Marnel Rodriguez

Hi Mkyong,

I have a situation.

For example, JsonOutputGenerator has a property called “fileName”. And i have two beans referring to it and wants to pass a fileName string.

I want to maintain a single JsonOutputGenerator instance. I don’t like a config like this.

MyFileNameValue

Is what I want even possible? I’ve been searching but I can’t find an answer to my question. Thanks!

Vivek
Guest
Vivek

Just FYI,

Please add your Spring-Output.xml in Spring-Common.xml using import Statment

<import resource="Spring-Output.xml" /> 

to load this bean configuration file.

Thanks,
Vivek

Vikram S
Guest
Vikram S
<beans>

    <import resource="services.xml"/>
    <import resource="resources/messageSource.xml"/>
    <import resource="/resources/themeSource.xml"/>

    <bean id="bean1" class="..."/>
    <bean id="bean2" class="..."/>

</beans>
Ramesh
Guest
Ramesh

Hi mkyoung,

${bean.value}

this ${bean.value} is from db. how do i set this value from db.
please let me know.

thanks

Soumyajyoti
Guest
Soumyajyoti

@Malte..

I am also new in Spring world.. But what I think is that, in the web.xml you should have to mention these configuration file names within tag.

Could someone confirms whether I am right or not.

soniya
Guest
soniya

nice tutorial !!!

Janak
Guest
Janak

Hi,
what is the exact life cycle of the bean if we are using annotation based configuration?

Thank you

Malte
Guest
Malte

When using two configuration files in the example (Spring-Common.xml
and Spring-Output.xml) how does Spring refers to these files. Are they implicit or are their names to be given to Spring somehow?

Rajesh Kumar
Guest
Rajesh Kumar

1. Spring take the XML which is mapped to ApplicationContext context. In this case, it should be mapped to Spring-Common.xml
2. Also, in Spring-Common.xml, the other XML (Spring-Output.xml) need to be imported.

ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {“Spring-Common.xml”});

It worked for me.

Thank You.

Rajesh Kumar
Guest
Rajesh Kumar
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {“Spring-Common.xml”,"Spring-Output.xml"});

alternatively to avoid imports.

Vikram S
Guest
Vikram S
dinesh tiwari
Guest
dinesh tiwari

Well Done !! This is another good example. Keep posting good stuff.

trackback
Spring Tutorials

[…] Bean reference in Spring How beans can access to each other by specify the bean references in the same or different bean configuration file. […]