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");
}
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。