demo下载地址:https://download.csdn.net/download/aggie4628/12673642
1.依赖注入
1.1构造器注入 对应:c命名空间
1.2 set 注入 对应:P命名空间
依赖:bean对象的创建依赖于容器。
注入:bean对象中的所有属性由容器注入。
2.自动装配
1.依赖注入
1.1构造器注入 对应:c命名空间
1.2 set 注入 对应:P命名空间
依赖:bean对象的创建依赖于容器。
注入:bean对象中的所有属性由容器注入。
如果出现以下:
2.自动装配,环境搭建:demo
2.1 3个DAO类 :Person,Dog,Cat
2.2 beans-person.xml
参数:byname 是变量名
参数:byType 是类名
bean中 id = 对应 类中的变量名
<property name="”> 对应 类中的属性名 (Person name)
<?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="cat" class="com.tang.Cat"/>
<bean id="dog" class="com.tang.Dog" />
<bean id="person" class="com.tang.Person" scope="singleton" autowire="byName">
<property name="name" value="2"></property>
</bean>
<bean id="user" class="com.tang.User" >
</bean>
</beans>
2.3 测试类
public class myTest {
@Test
void myTest1()
{
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-person.xml");
Person p =(Person) ctx.getBean("person",Person.class);//前面是变量 后面是类名
p.getDog().bark();
p.getCat().bark();
// System.out.println(p.getUserDAO());
}
}