Yair
Yair

Reputation: 518

Can one provide custom qualifier for beans defined with component scanning?

Having the following bean definitions in mind:

<bean id="bean1" class="com.mycompany.SomeClass">
   <property name="prop1" value="value1">
   <property name="prop2" value="value2">
</bean>
<bean id="bean2" class="com.mycompany.SomeClass">
   <property name="prop1" value="value3">
   <property name="prop2" value="value4">
</bean>

In an Annotation based environment, I can use the @Qualifier annotation to distinguish between the two:

@Autowired
@Qualifier("bean1")
private SomeClass first;

@Autowired
@Qualifier("bean2")
private SomeClass second;

Can I achieve the same thing if I don't want to declare the bean in an XML configuration file, but using the @Component Annotation? I couldn't find any way to inject two different beans of the same class, initialized with different parameter, using the @Autowired annotation.

Thanks.

Upvotes: 3

Views: 799

Answers (4)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

Here is how this can be achieved with Java @Configuration:

@Configuration 
public class Config {

    @Bean
    public SomeClass bean1() {
        SomeClass s = new SomeClass();
        s.setProp1(value1);
        s.setProp2(value2);
        return s;
    }

    @Bean
    public SomeClass bean2() {
        SomeClass s = new SomeClass();
        s.setProp1(value3);
        s.setProp2(value4);
        return s;
    }

}

Upvotes: 0

ach
ach

Reputation: 6234

It's just @Component("myBeanName")

Upvotes: 1

Nazar Annagurban
Nazar Annagurban

Reputation: 336

If you use @Component, how would you differentiate between bean1 and bean2 within SomeClass? If you want to avoid XML, you will have to use Java configuration class which defines these two beans with different properties.

See Spring Java Config.

Upvotes: 0

Niels Bech Nielsen
Niels Bech Nielsen

Reputation: 4859

From the javadoc

public abstract String value
The value may indicate a suggestion for a logical component name, to be turned into a Spring bean in case of an autodetected component.

Upvotes: 1

Related Questions