Understanding Spring @Autowired usage

前端 未结 3 914
臣服心动
臣服心动 2020-11-22 05:00

I am reading the spring 3.0.x reference documentation to understand Spring Autowired annotation:

3.9.2 @Autowired and @Inject

I am not able to understand the

3条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 05:23

    Nothing in the example says that the "classes implementing the same interface". MovieCatalog is a type and CustomerPreferenceDao is another type. Spring can easily tell them apart.

    In Spring 2.x, wiring of beans mostly happened via bean IDs or names. This is still supported by Spring 3.x but often, you will have one instance of a bean with a certain type - most services are singletons. Creating names for those is tedious. So Spring started to support "autowire by type".

    What the examples show is various ways that you can use to inject beans into fields, methods and constructors.

    The XML already contains all the information that Spring needs since you have to specify the fully qualified class name in each bean. You need to be a bit careful with interfaces, though:

    This autowiring will fail:

     @Autowired
     public void prepare( Interface1 bean1, Interface1 bean2 ) { ... }
    

    Since Java doesn't keep the parameter names in the byte code, Spring can't distinguish between the two beans anymore. The fix is to use @Qualifier:

     @Autowired
     public void prepare( @Qualifier("bean1") Interface1 bean1,
         @Qualifier("bean2")  Interface1 bean2 ) { ... }
    

提交回复
热议问题