Reputation: 22446
Say I have the following class:
@Service
public class Foo {
@Autowired
private MySvcClass svc;
}
If I use Spring's annotation initialization, Spring will iterate through all of its beans and if it has a single instance of MySvcClass
, it will inject it. I don't need to know the name of the instance of MySvcClass
, just that it's an instance of MySvcClass
.
How do I get the same result if I'm using the XML and not leveraging annotations?
For instance by xml def could look like:
<bean id="foo" class="Foo">
<property name="svc" ref="idOfMySvcClass"/>
</bean>
But this requires me to know the name of the MySvcClass
instance. Is there a way for Spring to use the same logic as above where I specify only the type and Spring will find my instance?
Upvotes: 2
Views: 2189
Reputation: 98
If you need not have to know the bean names, you can use 'autowiring by-type'.
Your XML configuration will look like this:
<bean id="foo" class="com.example.Foo" autowire="byType" />
<bean id="mySvcClass" class="com.example.MySvcClass" />
Note the 'autowire by type' attribute at Foo class.
The class definition will look like below:
package com.example;
public class Foo
{
private MySvcClass mySvcClass;
}
Upvotes: 4
Reputation: 3589
Add autowire="byType" attribute to your bean element in xml.
Upvotes: 2