Spring入門案例(Ioc 控制反轉)
阿新 • • 發佈:2018-12-17
1、首先匯入spring必須要的4個核心包(beans、core、context、expression)+1個依賴(commons-logging...jar)
2、目標類
提供UserService介面和實現類
package ioc;
public interface UserService {
public void addUser();
}
public class UserServiceImpl implements UserService { @Test public void addUser() { System.out.println("ioc add user"); } }
之前寫程式碼直接new一個例項,現在學習了spring之後,將由spring建立物件例項-->Ioc控制反轉(Inverse of Control)
之後需要例項物件時,從spring工廠(容器)中獲得,需要將實現類的全限定名稱配置到xml檔案中
3、配置檔案
位置一般放在classpath下(src),名字約定俗成的:applicationContext.xml。新增schema約束
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd "> <!-- 將user物件交給spring容器管理 <bean> 配置需要建立的物件 id:用於之後從spring容器獲得例項時使用 class:需要建立的全限定類名 --> <bean name="user" class="ioc.UserServiceImpl"></bean> </beans>
位置如圖:
4、測試