Spring IOC automatic assembly

Automated assembly

When you need to reference an object to another object in the previous configuration, we are to be manually configured by property tags, in fact, in spring also provides a very powerful feature is the automatic assembly, in accordance with our designated rules configuration, the configuration of the following ways:

<bean id="address" class="com.nanborone.bean.Address">
    <property name="province" value="辽宁" />
    <property name="city" value="沈阳" />
    <property name="town" value="浑南" />
</bean>
<bean id="book" class="com.nanborone.bean.Book">
    <property name="name" value="" />
    <property name="author" value="作者" />
    <property name="price" value="122" />
</bean>
<!-- 默认不自动装配,等同于defalult/no -->
<bean id="person" class="com.nanborone.bean.Person" />
<!-- 按照名字进行装配,以setXXX方法的XXX作为id去容器中查找组件,进行赋值,如果找不到则装配为null -->
<bean id="person1" class="com.nanborone.bean.Person" autowire="byName" />
<!-- 按照类型进行装配,以属性的类型作为查找依据去容器中找到这个组件,通过set方法注入,如果定义两个相同类型的bean,则直接报错 -->
<bean id="person2" class="com.nanborone.bean.Person" autowire="byType" />
<!-- 按照构造器进行装配,需要有一个构造方法,仅包含自动装配的bean的参数,否则不会生效 -->
<!-- 例如下例中装配address和一个book,如果没有定义address、book两个参数的构造则不能正确装配。如果是多一个参数,则全部自动装配为null,如果少一个参数,则按照构造方法定义的顺序装配后定义的,先定义装配为null -->
<!-- 如果定义两个相同类型的bean,会装配beanId与构造方法参数名一致的那个,否则装配null -->
<bean id="person3" class="com.nanborone.bean.Person" autowire="constructor" />

Priority injection

<!-- 当自动装配时发现多个符合装配条件的bean,则指定primary为true的装配 -->
<bean id="address" class="com.nanborone.bean.Address" primary="true" />

Remove the automatic assembly

<!-- 当前bean不参与自动装配,不会以自动装配的形式注入到其他bean中,但不会影响显示引用 -->
<bean id="address" class="com.nanborone.bean.Address" autowire-candidate="false" />

Pattern Matching

<!-- 仅自动装配标识以Repository结尾的bean,如果在bean上显示定义了autowire-candidate属性,则不使用模式匹配 -->
<beans default-autowire-candidates="*Repository">
Published 13 original articles · won praise 0 · Views 324

Guess you like

Origin blog.csdn.net/weixin_44601009/article/details/104310087