DI(dependency Injection)---依赖注入
什么是依赖注入:
通过给bean属性注入值。注入的这个过程叫做依赖注入。PPT中解释是DI:Dependency Injection 依赖注入,Spring框架负责创建Bean对象时,动态的将依赖对象注入到Bean组件。
代码演示:
beans.xml
beans.xml
向service中的name属性注入值。
<bean id="userService" class="cn.itcast.service.UserService">
<property name="name" value="张三"></property>
</bean> |
UserService.java
package cn.itcast.service;
/*
* 代表业务层组建
* */
public class UserService {
private String name;
/*
* 模拟保存操作
* */
public void save(){
System.out.println("保存用户..."+name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} |
SpringTest.java
package test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.service.UserService;
public class SpringTest {
//测试spring工厂
@Test
public void test(){
//将UserService对象的创建交给spring。直接从spring工厂中获取
//读取spring配置文件创建spring工厂
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
//从工厂中获取对象
UserService us = (UserService) ctx.getBean("userService");
us.save();
}
} |