IOC 工程配置步驟
- 引入 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 |
- 在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>
- 創建實體類
這個實體類要在 beans.xml 中進行配置
package com.sfox.bean;
public class UserBean {
public void add(String flg){
System.out.println("add......." + flg);
}
}
- 在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>
- 最會使用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");
}
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。