一、spring的简单介绍:
spring是一个好使而又简单的轻量级框架,对于简单的使用,我们只需理解IOC(控制反转)。对于IOC的简单理解就是只需明白把对象的创建权交给了spring,我们在程序代码中所需要的对象,都由Spring创建,而且是单例模式,也就是spring拥有单例模式的优点。
此次演示的功能:通过spring的IOC获得学生对象,通过该对象调用student的show方法。
二、spring的简单使用:
1.我们需要在我们的项目中导入spring的jar包
2.创建实体类,此处我创建的是学生类,里面包含get、set方法、还有一个show方法
package com.lili.pojo;
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void show()
{
System.out.println(name+"今年"+age+"岁!");
}
}
3.我们要使用spring,很大一部分使用前工作就是配置xml文件。现在开始创建并配置spring的xml文件。
在项目中创建spring的xml文件,文件名随意,但是大多叫applicationContext.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="stu" class="com.lili.pojo.Student">
<!-- 这里的name值与set里的方法名有关,不一定与属性相同 -->
<property name="name" value="李白"/>
<property name="age" value="18"/>
</bean>
</beans>
4.创建测试类,完成测试功能。
package com.lili.spring1;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.lili.pojo.Student;
public class Test {
public static void main(String[] args) {
//加载配置文件
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//获取student对象,通过spring的IOC由spring创建对象
Student stu=(Student) ac.getBean("stu");
Student stu2=(Student) ac.getBean("stu");
Student stu3=(Student) ac.getBean("stu");
//调用student中的方法
//spring采用的是单例模式
stu.show();
stu2.show();
stu3.show();
}
}
5.结果: