Spring

Spring自动装配

rzk · 3月29日 · 2020年本文共1071个字 · 预计阅读4分钟145次已读
applocationCo睿共享ntext.xml


       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="ht睿共享tp://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://ww睿共享w.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd"
>
    
    
    class="com.rzk.pojo.Dog">
    class="com.rzk.pojo.Cat">
    
    class="com.rzk.pojo.People" autowire="byName">
   class="com.rzk.pojo.People" autowire="byType">
public class Cat {
    public void shout(){
        System.out.println("猫叫");
    }
}
public class Dog {
    public void shout(){
        System.out.println("狗叫");
    }
}
public class People {
    private Cat cat;
  睿共享  private Dog dog;
    private String name;

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "People{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + ''' +
                '}';
    }
}
测试类
public
class MyTest { @Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("applocationContext.xml"); People people = context.getBean("people", People.class); people.getCat().shout(); people.getDog().shout(); } }

自动转配:autowire
1)autowire=”byType”根据类型,自动导入需要的类属性,如果定义的类属性是单个,导入的类属性有>=2个类实例,报错睿共享
如果定义的类属性是集合,导入的类属性有>=2个类实例没问题
2)autowire=”byName”根据类中定义的类属性的名字,如果bean中有>=2的类属性的实例,报错

byName: 会自动在容器上下文查找,和自己对象set方法后面的值对应的 bean id
byType: 会自动在容器上下文查找,和自己对象属性类名相同的bean

byName: 会自动在容器上下文查找,和自己对象set方法后面的值对应的 bean id
byType: 会自动在容器上下文查找,和自己对象属性类名相同的bean
0 条回应