注入:通过 Spring 工厂及配置文件,为所创建对象的成员变量赋值。
为什么要注入?- 通过编码的方式,为成员变量进行赋值,存在耦合。
- 注入的好处:解耦合。
public void test4() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
Person person = (Person) ctx.getBean("person");
// 通过代码为变量赋值, 存在耦合, 如果我们以后想修改变量的值, 需要修改代码, 重新编译
person.setId(1);
person.setName("zhenyu");
System.out.println(person);
}
如何进行注入[开发步骤]
- 类的成员变量提供 set get 方法
- 配置 spring 的配置文件
10 leon



