IOC(控制反轉) & DI(依賴注入)
阿新 • • 發佈:2018-12-21
一、IOC(控制反轉)
二、DI(依賴注入)
DI Dependency Injection 依賴注入的概念,就是在Spring建立這個物件的過程中,將這個物件所依賴的屬性注入進去。
程式碼:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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"> <!-- UserService的建立權交給了Spring --> <bean id="userService" class="com.imooc.ioc.demo1.UserServiceImpl"> <property name="name" value="李四"/> </bean> </beans>
package com.imooc.ioc.demo1;
/**
* Created by jt on 2017/10/8.
*/
public interface UserService {
public void sayHello();
}
package com.imooc.ioc.demo1; /** * Created by jt on 2017/10/8. */ public class UserServiceImpl implements UserService{ // 新增屬性: private String name; public void sayHello() { System.out.println("Hello Spring" + name); } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.imooc.ioc.demo1; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; /** * Created by jt */ public class SpringDemo1 { @Test /** * 傳統方式開發 */ public void demo1(){ // UserService userService = new UserServiceImpl(); UserServiceImpl userService = new UserServiceImpl(); // 設定屬性: userService.setName("張三"); userService.sayHello(); } @Test /** * Spring的方式實現 */ public void demo2(){ // 建立Spring的工廠 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); // 通過工廠獲得類 UserService userService = (UserService)applicationContext.getBean("userService"); userService.sayHello(); } }