DI(Dependency Injection),依赖注入是一种技术,即一个对象提供另一个对象的依赖关系。
构造注入
前提:类型必须有构造,index与参数类型保持一致
1.创建Student类
package cn.happy.day03aop.aop;/** * Created by Administrator on 2018/3/5. *///构造注入public class Student { private String name; private Integer age; public Student() { } public Student(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; }}
2.配置applicationContext.xml文件
3.编写测试类
@Test public void SpringStructure(){ ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext-day04di.xml"); Student service=(Student)ctx.getBean("dao"); System.out.println( service.getName()+"\n"+service.getAge()); }
4.查看测试结果
p命名空间的注入
使用前要先要在applicationContext.xml配置文件中引入p命名空间
xmlns:p="http://www.springframework.org/schema/p"1.1创建一个Car类
public class Car { private String color; public String getColor() { return color; } public void setColor(String color) { this.color = color; }}
1.2在Student类中加入一个Car类型的car属性,并封装
2.配置applicationContext.xml
3.查看测试结果
集合属性注入
1.创建Mycollection类
package cn.happy.day03aop.aop;import java.util.*;/** * Created by Administrator on 2018/3/5. *///集合属性注入public class Mycollection { private String[] array; private Listlist; private Set set; private Map map; private Properties properties; @Override public String toString() { return "Mycollection{" + "array=" + Arrays.toString(array) + ", list=" + list + ", set=" + set + ", map=" + map + ", properties=" + properties + '}'; } public String[] getArray() { return array; } public void setArray(String[] array) { this.array = array; } public List getList() { return list; } public void setList(List list) { this.list = list; } public Set getSet() { return set; } public void setSet(Set set) { this.set = set; } public Map getMap() { return map; } public void setMap(Map map) { this.map = map; } public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; }}
2.配置applicationContext.xml
小李 小王
小张 小黄 小赵 小辉 1 2
3.测试
分享完毕