在Spring中通过构造自动装配--constructor

在Spring中,可以使用“通过构造自动装配”,实际上是按构造函数的参数类型自动装配。 这意味着,如果一个bean的数据类型与其他bean的构造器参数的数据类型是相同的,那么将自动装配。

 

package auto_constructor;

/**
 * Created by luozhitao on 2017/8/9.
 */
public class student {

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private  String name;
}

 

package auto_constructor;

/**
 * Created by luozhitao on 2017/8/9.
 */
public class school {

    public school(student st) {
        this.st=st;
    }

    public student getSt() {
        return st;
    }

    private student st;
}

 

 <!--  构造方法注入   实际上是按构造函数的参数类型自动装配  -->
    <bean id="student" class="auto_constructor.student">
        <property name="name" value="猫儿"></property>
    </bean>
    <bean id="school" class="auto_constructor.school" autowire="constructor"></bean>

 

在Spring,“通过自动检测自动装配”是指选,如果有默认构造函数(参数与任何数据类型)则安装构造函数注入,若没有构造函数则以“按类型自动装配”。

 <bean id="student" class="auto_constructor.student">
        <property name="name" value="猫儿"></property>
    </bean>
    <bean id="school" class="auto_constructor.school" autowire="autodetect"></bean>

 

posted on 2017-08-09 11:39  猫儿爹  阅读(1067)  评论(0编辑  收藏  举报

导航