一、自动装配
该篇文章讲自动装配。使用的是xml配置文件方式。
项目结构:
创建实体类
public class Cat {
}
public class Dog {
}
public class People {
private Cat cat;
private Dog dog;
@Override
public String toString() {
return "People{" +
"cat=" + cat +
", dog=" + dog +
'}';
}
public People() {
}
public People(Cat cat, Dog dog) {
this.cat = cat;
this.dog = dog;
}
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;
}
}
编写配置文件。
注意:如果使用autowire=“constructor”,则自动装配的类中,需要有所有属性的带参构造器。
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="cat" class="com.shengjava.pojo.Cat"/>
<bean id="dog" class="com.shengjava.pojo.Dog"/>
<!-- 没有使用自动装配之前,我们需要自己手动注入对象到People对象的属性中(使用People类的无参构造器) -->
<bean id="peopleBefore" class="com.shengjava.pojo.People">
<property name="cat" ref="cat"></property>
<property name="dog" ref="dog"></property>
</bean>
<!-- 使用自动装配之后则不需要。autowire属性:byType(依靠类型)、byName(依靠变量名和bean的id)、constructor(类似于byType,要有带参构造器)、no(默认为no,不使用自动装配)-->
<bean id="peopleAfter" class="com.shengjava.pojo.People" autowire="byType"></bean>
</beans>
测试类
public class PeopleTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// 没有使用自动装配之前
People peopleBefore = context.getBean("peopleBefore", People.class);
System.out.println(peopleBefore);
// 使用自动装配
People peopleAfter = context.getBean("peopleAfter", People.class);
System.out.println(peopleAfter);
}
}
输出
People{cat=com.shengjava.pojo.Cat@49d904ec, dog=com.shengjava.pojo.Dog@48e4374}
People{cat=com.shengjava.pojo.Cat@49d904ec, dog=com.shengjava.pojo.Dog@48e4374}
以上就是自动装配,现在是使用的xml配置方式,但是这种方式比较复杂,后面会有更简单的自动装配方式(使用注解)。
参考:1.4.5. Autowiring Collaborators
相关
我的该分类的其他相关文章,请点击:【Spring】文章目录