How do I inject a Spring dependency by ID?

后端 未结 1 1986
轻奢々
轻奢々 2020-12-28 15:10

I have several beans with the same type (BeanType). How do I inject them by ID with an annotation? Say:

@Autowired @ID(\"bean1\")
public void se         


        
相关标签:
1条回答
  • 2020-12-28 15:48

    Simplest solution is to use @Resource

    @Resource(name="bean1")
    public void setBean( BeanType bean ) {
    }
    

    Incidentally, @Qualifier is used to refer to beans by ID for use with @Autowired, e.g

    @Autowired @Qualifier("bean1")
    public void setBean( BeanType bean ) {
    }
    

    where bean1 is the ID of the bean to be injected.

    See the Spring manual:

    For a fallback match, the bean name is considered a default qualifier value. Thus you can define the bean with an id "main" instead of the nested qualifier element, leading to the same matching result. However, although you can use this convention to refer to specific beans by name, @Autowired is fundamentally about type-driven injection with optional semantic qualifiers. This means that qualifier values, even with the bean name fallback, always have narrowing semantics within the set of type matches; they do not semantically express a reference to a unique bean id.

    and

    If you intend to express annotation-driven injection by name, do not primarily use @Autowired, even if is technically capable of referring to a bean name through @Qualifier values. Instead, use the JSR-250 @Resource annotation, which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.

    I prefer @Resource, it's cleaner (and not Spring-specific).

    0 讨论(0)
提交回复
热议问题