DI:Dependency Injection 依赖注入,在Spring框架负责创建Bean对象时,动态的将依赖对象注入到Bean组件
(简单的说,可以将另外一个bean对象动态的注入到另外一个bean中。)
【面试题】IoC和DI的区别 ?
DI和IoC是同一件事情,都是将对象控制权交给第三方(Spring)管理,只是站在不同角度而已。
即:Spring创建了Service、DAO对象,在配置中将DAO传入Servcie,那么Service对象就包含了DAO对象的引用。
实例练习:即在业务层的service对象注入dao属性
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:spring创建的(UserDaoImpl)对象实例
id 或name都是给对象起名字,
class:指定创建哪个对象的实例
-->
<bean name="userservice" class="com.spring.quickstart.UserServiceImpl">
<!--
property:注入的属性
name:根据name来注入相应属性setXxx方法里面的xxx(小写),
ref:引用哪个对象,把userdao这个对象赋值给了userservcie对象
的一个成员变量dao(实际上是使用反射调用了setter方法赋值)
value:是赋值
-->
<property name="dao" ref="userdao">
</property>
</bean>
<bean name="userdao" class="com.spring.quickstart.UserDaoImpl"/>
</beans>
表现层:
package com.spring.quickstart;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class SpringTest {
@Test
public void login(){
// UserService service = new UserServiceImpl();
//使用spring ioc控制创建实例
//spring工厂,也称spring容器,或者叫bean容器
ApplicationContext applicationContext =
new FileSystemXmlApplicationContext("src/ApplicationContext.xml");
UserService service = (UserService) applicationContext.getBean("userservice");
service.login();
}
}
业务层:
package com.spring.quickstart;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class UserServiceImpl implements UserService {
private UserDao dao;
//需要使用setter方法注入属性
public void setDao(UserDao dao) {
this.dao = dao;
}
public void login() {
// ApplicationContext applicationContext =
// new FileSystemXmlApplicationContext("src/ApplicationContext.xml");
// ApplicationContext applicationContext =
// new ClassPathXmlApplicationContext("ApplicationContext.xml");
// UserDao dao =(UserDao) applicationContext.getBean("userdao");
// UserDao dao = new UserDaoImpl();
dao.login();
}
public void reg(){
// ApplicationContext applicationContext =
// new ClassPathXmlApplicationContext("ApplicationContext.xml");
// UserDao dao =(UserDao) applicationContext.getBean("userdao");
dao.reg();
}
}
持久层:
package com.spring.quickstart;
public class UserDaoImpl implements UserDao {
public void login() {
System.out.println("用户登录了......");
}
public void reg() {
System.out.println("用户注册......");
}
}