Is it possible to provide a custom classifier for beans defined using bean scanning?

With 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 annotation @Qualifier

to differentiate between the two:

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

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

      

Can I achieve the same if I don't want to declare the bean in the XML config file, but using @Component

Annotation? I couldn't find a way to inject two different beans of the same class initialized with a different parameter using annotation @Autowired

.

Thank.

+3


source to share


4 answers


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

      

+1


source


It's simple @Component("myBeanName")



+1


source


If you are using @Component, how would you distinguish between bean1 and bean2 in SomeClass? If you want to avoid XML, you will have to use a Java config class that defines these two beans with different properties.

See Spring Java Configuration .

0


source


This is how it 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;
    }

}

      

0


source







All Articles