Question

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?

Was it helpful?

Solution

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;

}

OTHER TIPS

Add autowire="byType" attribute to your bean element in xml.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top