Reference an Annotated Spring Component in an XML Bean Definition

Mike Rylander picture Mike Rylander · Jul 5, 2013 · Viewed 18.6k times · Source

I am using an external library that requires that I configure it using an XML Bean definition; in the Bean definition I need to provide an external class with a Bean from my project. I am using spring annotations with component scanning.

How do I reference my annotated Bean within the XML Bean Definition?

Are there any alternatives to creating an XML Bean Definition?

Details: Spring 3.0.7

Answer

Costi Ciudatu picture Costi Ciudatu · Jul 6, 2013

No matter how it got created (based on XML- or annotation- metadata), every bean ends up in the application context under a unique name.

If you've just annotated your class with @Component or derivatives, without stating any name, the default naming scheme will be applied and the bean name will be your class name with the first character lowercased: ClassName => "className".

With that in mind, if you need to inject that bean in an XML bean definition, you do it like with any other bean in your context:

<bean id="someBean" class="SomeClass">
    <property name="someProp" ref="className"/><!-- to stick to the above example -->
</bean>

Since you're mixing annotations with XML, the application context will be able to locate the "className" bean properly.