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("使用者注冊......");
}
}