Spring_2 IOC 入門示例

IOC 工程配置步驟

  1. 引入 jar 包
    這里引入的jar 只是實習 IOC 功能,實際還有許多jar 需要引入。
包名
commons-logging-1.1.3.jar
spring-beans-4.2.4.RELEASE.jar
spring-context-4.2.4.RELEASE.jar
spring-core-4.2.4.RELEASE.jar
spring-expression-4.2.4.RELEASE.jar
  1. 在src目錄下創建beans,xml 文件,并對配置schema 文件(可在幫助文檔中和示例中找到)
<?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">
    
</beans>
  1. 創建實體類
    這個實體類要在 beans.xml 中進行配置
package com.sfox.bean;

public class UserBean {
    public void add(String flg){
        System.out.println("add......." + flg);
    }
}

  1. 在beans.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 id="userBean" class="com.sfox.bean.UserBean"/>
</beans>
  1. 最會使用junit 進行測試
    創建一個測試類,在使用junit測試時,我們首先要確認工程中要引入junit 的jar。
    我們在該測試類中使用ApplicationContext加載配置的beans.xml文件。
    在下面的代碼中使用@Test注解
    注意下面示例代碼中包得引入路徑
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sfox.bean.UserBean;

public class TestIop {
    
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserBean user = (UserBean) context.getBean("userBean");
        user.add("bean");
    }
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,993評論 19 139
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,973評論 6 342
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,779評論 18 399
  • 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente...
    SnailTyan閱讀 4,206評論 2 7
  • 一. Java基礎部分.................................................
    wy_sure閱讀 3,839評論 0 11