1.在xml中显示的配置
2.在java中显示配置
3.隐式的自动装配bean【重点掌握】
创建3个实体类
public class Dog {
public void shout(){
System.out.println("旺~");
}
}
public class Cat {
public void shout(){
System.out.println("喵~");
}
}
@Data
public class People {
private Cat cat;
private Dog dog;
private String name;
}
配置文件
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="dog" class="com.saxon.pojo.Dog"/>
<bean id="cat" class="com.saxon.pojo.Cat"/>
<bean id="people" class="com.saxon.pojo.People">
<property name="name" value="saxon"/>
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
</bean>
</beans>
测试类:
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
People people = context.getBean("people", People.class);
people.getCat().shout();
people.getDog().shout();
}
}
beans.xml文件中,加入autowire属性,将值设置为byName
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid
<?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="dog" class="com.saxon.pojo.Dog"/>
<bean id="cat" class="com.saxon.pojo.Cat"/>
<bean id="people" class="com.saxon.pojo.People" autowire="byName">
<property name="name" value="saxon"/>
</bean>
</beans>
bytype自动装配和byname的差不多,将autowire的值设置为byType
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean,但是一种属性只能有一个对象,否则spring容器无法进行识别,这里装配方式的id是可以省略的
<?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="dog" class="com.saxon.pojo.Dog"/>
<bean id="cat" class="com.saxon.pojo.Cat"/>
<bean id="people" class="com.saxon.pojo.People" autowire="byType">
<property name="name" value="saxon"/>
</bean>
</beans>
原文:https://www.cnblogs.com/saxonsong/p/14900268.html