Spring: Attaching @Qualifer to Java-configured beans

41,411

Solution 1

If you're using annotations (not Java based configuration), you can use the following to add a qualifier (see the Spring documentation):

@Component
@Qualifier("myQualifier")
public class MyBean {
    //code
}

And to wire in the bean, use the following (again, see the Spring documentation):

public class MyClass {

    @Autowired
    @Qualifier("myQualifier")
    private MyBean myBean;

    //more code

}

Solution 2

What, like @Qualifier, you mean?

3.10.4 Defining bean metadata within components

Example:

  @Bean @Qualifier("public")
  public TestBean publicInstance() {
      return new TestBean("publicInstance");
  }
Share:
41,411
Aleksandr Dubinsky
Author by

Aleksandr Dubinsky

Updated on February 08, 2020

Comments

  • Aleksandr Dubinsky
    Aleksandr Dubinsky over 4 years

    In spring, you can XML-configure a bean to have a qualifier. I can't seem to find how I can attach a qualifier if configuring beans through Java annotations. What's up with that? Do I have to use just plain old names?

  • Snowy Coder Girl
    Snowy Coder Girl over 12 years
    +1. See also my answer for autowiring (didn't add it here b/c code would be hard to read).
  • Nick
    Nick over 7 years
    And what's wrong with @Component("componentName")? How @Component @Qualifier is better?
  • levant pied
    levant pied over 5 years
    @Nick You can qualify multiple components with the same qualifier. Think of it as a grouping concept.