开发者

Autowiring priority

开发者 https://www.devze.com 2023-02-19 16:03 出处:网络
<beans default-autowire=\"byType\" /> means that all fields of beans will automatically have dependencies injected if there is no more than 1 bean with the desired type.
<beans default-autowire="byType" />

means that all fields of beans will automatically have dependencies injected if there is no more than 1 bean with the desired type.

I wonder if there is a way to define some sort of pri开发者_JS百科ority order (based on naming convention for example) for the auto-wiring in the case where there are more than one bean of the desired type.

Thanks in advance.

Edit: I just want to add that i'm not allowed to use annotations such as @Component and @Qualifier in the project i'm currently working on.


No there is not, but you can override this behavior as needed for each bean e.g.specify something like this where required:

<beans default-autowire="byType" >
    <bean id="..." autowire="byName">
        ....
    </bean>
</beans>

From spring 2.5 upwards when using the <context:component-scan/> to autowire beans via @Autowired you can also add @Qualifier where needed to specify a bean by name if there are multiple beans of the same type.

As stated in the spring documentation there are a few different ways to specify autowiring:

  • no - do not autowire, this is the default
  • byType - property type must match bean type, if more than one bean of that type is exists then an exception is thrown
  • byName - bean name must match property name
  • constructor - basically the same as byType but for constructors, spring picks the constructor with the most matches
  • autodetect - same as byType unless there is no default constructor where it falls back to constructor autowiring
0

精彩评论

暂无评论...
验证码 换一张
取 消