Spring自动装配
applocationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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="http://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://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd" > <context:annotation-config/> <!-- 如果设置了byName 的话会直接找 id 如果设置了byType 的话会直接找 class属性所对应的类名 --> <bean id="dog" class="com.rzk.pojo.Dog"></bean> <bean id="cat" class="com.rzk.pojo.Cat"></bean> <!-- byName: 会自动在容器上下文查找,和自己对象set方法后面的值对应的 bean id byType: 会自动在容器上下文查找,和自己对象属性类名相同的bean --> <bean id="people" class="com.rzk.pojo.People" autowire="byName">
<bean id="people" class="com.rzk.pojo.People" autowire="byType">
</bean> </beans>
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