1.创建web项目
2.引入jar包
3.引入日志配置文件
log4j.properties
4.创建一个java类
package ar.bdqn.spring.pojo;
public class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
System.out.println("构造方法被调用");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
5.创建Bean容器
名字路径没有什么特殊要求。
applicationContext-xml
放在resources资源文件下面
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
</beans>
6.配置Bean对象
<!-- Bean:容器创建Person的对象 -->
<!-- name: 相当变量名Person p = new Person(); -->
<!-- class: 类的全限定名 -->
<bean name="p" class="ar.bdqn.spring.pojo.Person"></bean>
#7.测试用例
package ar.sprin.pojo;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import ar.bdqn.spring.pojo.Person;
public class IOCTest {
private String file="application.xml";
@Test
public void testCreatPerson(){
//读取配置文件(创建容器)
ApplicationContext context=new ClassPathXmlApplicationContext(file);
//查找对象
Person p=(Person)context.getBean("p");
System.out.println(p);
}
}