DI:依赖注入
属性赋值有两种方式:构造方法、访问器
光靠构造方法赋值,在实际应用中远远不够
AOP是方法论,DI是具体手段
两注入方式
1、通过“构造器”注入
2、通过“访问器”注入
访问器赋值
例:狗和主人
----涉及到基本类型、String类型、自定义类型、数组类型、三种集合的赋值
主人类
public class DogMst {
DogMst (){
System.out.println("狗主人的构造方法"+getClass());
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "DogMst [name=" + name + "]";
}
}
狗类
public class Dog {
public Dog() {
System.out.println("狗的构造器"+getClass());
}
private String name;
private String alias;
private int age;
private DogMst master;
private Object[] obj;
private List favList;
private Set favSet;
private Map favMap;
public void setName(String name) {
this.name = name;
}
public void setAlias(String alias) {
this.alias = alias;
}
public void setAge(int age) {
this.age = age;
}
public void setMaster(DogMst master) {
this.master = master;
}
public void setObj(Object[] obj) {
this.obj = obj;
}
public void setFavList(List favList) {
this.favList = favList;
}
public void setFavSet(Set favSet) {
this.favSet = favSet;
}
public void setFavMap(Map favMap) {
this.favMap = favMap;
}
@Override
public String toString() {
return "Dog [name=" + name + ", alias=" + alias + ", age=" + age
+ ", master=" + master + ", obj=" + Arrays.toString(obj)
+ ", favList=" + favList + ", favSet=" + favSet + ", favMap="
+ favMap + "]";
}
}
applicationContext.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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dog" class="p05.Dog" scope="prototype">
<!-- String:value 两种写法 -->
<property name="name" value="来福"></property>
<property name="alias">
<value>牧羊犬</value>
</property>
<!-- 整形 -->
<property name="age" value="2"></property>
<!-- 对象类型注值 -->
<property name="master">
<ref bean ="mst"/>
</property>
<!-- 数组(list):用的object类型 -->
<property name="obj">
<list>
<value>object数组</value>
<value>2</value>
<ref bean="mst" />
</list>
</property>
<property name="favList">
<list>
<value>List骨头</value>
<value>List飞盘</value>
<value>List睡觉</value>
</list>
</property>
<property name="favSet">
<set>
<value>Set骨头</value>
<value>Set飞盘</value>
<value>Set睡觉</value>
</set>
</property>
<property name="favMap">
<map>
<entry key="A" value="骨头" />
<entry key="B" value="飞盘" />
<entry key="C" value="睡觉" />
</map>
</property>
</bean>
<bean id="mst" class="p05.DogMst" >
<property name="name" value="Bob"></property>
</bean>
</beans>
测试类
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("p05/applicationContext.xml");
Dog dog = ac.getBean(Dog.class);
System.out.println(dog);
}
}