Spring环境搭建
- 创建好web项目之后进行以下操作
?
一、导入jar包
- 搭建Spring环境需要引入Spring必须的4个jar包
- spring-beans.jar 【spring容器管理对象的主要jar包】
- spring-core.jar 【spring核心包】
- spring-context.jar 【spring上下文相关jar包】
- spring-expression.jar 【spring表达式相关jar包】
- 如果需要查看相关日志,也可以导入commons-logging.jar
二、创建applicationContext.xml
- 在src下创建一个名为applicationContext的xml文件
三、写入schema
- spring配置文件中使用的是schema(DTD的升级版)
这里的引入头可以直接使用
<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>
四、创建实体类
- 因为Spring中Ioc的作用是对象管理,所以我们需要使用一个实体类来测试我们的环境是否搭建成功了
public class Student {
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
super();
System.out.println("这里是student构造方法");
}
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;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
五、在applicationContext.xml 中通过bean标签引入类
- 使用bean标签引入实体类到我们的配置文件中
<bean id="stu" class="com.xc.bean.Student"></bean>
其中class写的是被spring管理类的全路径
id值的是我们在测试引用的实体名称
六、创建测试类
public static void main(String[] args) {
ApplicationContext a = new ClassPathXmlApplicationContext("applicationContext.xml");
Student bean = a.getBean(Student.class, "stu");
System.out.println(bean);
}
由第一次学习可知:ApplicationContext是实现了BeanFactory的接口,他扩展了很多其他方法和类,我们通过ClassPathXmlApplicationContext()方法可以通过配置文件名称连接spring容器
运行结果为:
- 根据结果可知我们输出的对象不是null,证明该对象被创建了,我在构造方法中打印了一句话,构造方法是什么时候被调用的呢?我们来测试一下
测试构造方法
- 我们修改一下测试方法,我们只加载配置文件,不通过bean工厂创建对象
由结果可知,类的构造方法会在配置文件加载的时候调用