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.

21 comments on “Spring bean reference example

  1. ref local is not supported anymore after spring 4.0

    Reply
    1. Is idref local not supported as well after spring 4.0?

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

    Reply
  3. myyong can you please tell me better way of learning

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

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

    Reply
  6. 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!

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

    Reply
    1. 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.

      Reply
  8. 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

    Reply
  9. <beans>
    
        <import resource="services.xml"/>
        <import resource="resources/messageSource.xml"/>
        <import resource="/resources/themeSource.xml"/>
    
        <bean id="bean1" class="..."/>
        <bean id="bean2" class="..."/>
    
    </beans>
    Reply
  10. Hi mkyoung,

    ${bean.value}

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

    thanks

    Reply
  11. @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.

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

    Thank you

    Reply
  13. 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?

    Reply
    1. 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.

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

        alternatively to avoid imports.

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

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *