IOC 工程配置步驟
- 引入 jar 包
這里引入的jar 只是實習(xí) 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目錄下創(chuàng)建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>
- 創(chuàng)建實體類
這個實體類要在 beans.xml 中進(jìn)行配置
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 進(jìn)行測試
創(chuàng)建一個測試類碌嘀,在使用junit測試時杜跷,我們首先要確認(rèn)工程中要引入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");
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者