自动装配是Spring满足Bean依赖的一种方式;Spring会在上下文自动寻找,并自动给bean装配属性。
在Spring中有三种装配的方式:
- 在xml中显示的配置;
- 隐式的自动装配bean【重要】;
- 在Java中显示配置。
1、搭建环境
-
编写实体类;
package com.beyond.pojo; public class Cat { public void shut(){ System.out.println("喵~"); } }
package com.beyond.pojo; public class Dog { public void shut(){ System.out.println("汪~"); } }
package com.beyond.pojo; public class People { private String name; private Cat cat; private Dog dog; public String getName() { return name; } public void setName(String name) { this.name = 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; } @Override public String toString() { return "People{" + "name='" + name + '\'' + ", cat=" + cat + ", dog=" + dog + '}'; } }
-
编写beans.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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="cat" class="com.beyond.pojo.Cat"/> <bean id="dog" class="com.beyond.pojo.Dog"/> <bean id="people" class="com.beyond.pojo.People"> <property name="name" value="小明"/> <property name="cat" ref="cat"/> <property name="dog" ref="dog"/> </bean> </beans>
-
测试。
import com.beyond.pojo.People; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { @Test public void test01(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); People people = context.getBean("people", People.class); people.getCat().shut(); people.getDog().shut(); } }
2、byName自动装配
-
编写beans.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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="cat" class="com.beyond.pojo.Cat"/> <bean id="dogccwd" class="com.beyond.pojo.Dog"/> <!-- autowire="byName"表示会自动在容器上下文中查找,和自己对象set方法后面的值对应的 beanid --> <bean id="people" class="com.beyond.pojo.People" autowire="byName"> <property name="name" value="小明"/> </bean> </beans>
-
测试。
import com.beyond.pojo.People; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { @Test public void test01(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); People people = context.getBean("people", People.class); /* 喵~ java.lang.NullPointerException 空指针异常 at MyTest.test01(MyTest.java:13) */ people.getCat().shut(); people.getDog().shut(); } }