标题创建pojo项目
首先要引入 spring的JAR包
commons-logging-1.2.jar
spring-aop-4.2.4.RELEASE.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
创建实体类
package students;
public class Student {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
}
application.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" default-lazy-init="default">
<!--bean 相当Student student=new Student(); lazy-init使用延迟该类 -->
<bean id="student" class="students.Student" lazy-init="true">
<!--property 对该Student属性name赋值=张三 -->
<property name="name" value="张三"></property>
<!--property 对该Student属性id赋值=1 -->
<property name="id" value="1"></property>
</bean>
</beans>
测试类
package Test;
import javax.annotation.Resource;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import students.Student;
public class TestSpring {
public static void main(String[] args) {
//lazy-init="true"-----------延迟设置---默认false
//SpringIOC容器bean:创建对象,给对象属性赋值
//上下文对象
ApplicationContext context=new ClassPathXmlApplicationContext("application.xml");
Student stu=(Student)context.getBean("student");
stu.setId(2);
System.out.println(stu.toString());
//或-------context1.getBean不用强转类型,后面直接引用
/*ApplicationContext context1=new ClassPathXmlApplicationContext("application.xml");
Student stu1=context1.getBean("student",Student.class);
stu.setId(2);
System.out.println(stu.toString());
*/
//方式二------------过时了
//解析配置文件
/* Resource resource=(Resource) new ClassPathResource("application.xml");
//获取BeanFoctory
BeanFactory beanfactory=new XmlBeanFactory(resource);
Student stu1= beanfactory.getBean("student",Student.class);
System.out.println(stu1.toString());
*/
}
//ApplicationContext与Resource区别
//ApplicationContext当web启动就---实例对象了
//Resource当web启动时还要获取BeanFactory---才实例对象了
}