Spring入门案例
第一步:创建工程 -> new Project 直接创建空工程即可
第二步:创建maven工程 启用模板
第三步:创建必要的文件 搭建环境
1.在main目录下创建resources目录
2.在test下也创建resources目录
第四步:修改pom文件
4.1把版本改成1.8
4.2 添加Spring的依赖(版本采用5.3.5)
4.3 相关配置
第五步:resources目录下创建Spring配置文件applicationContext.xml
至此,环境搭建完毕。
下面开始进行入门案例的准备
利用单元测试分别演示自己创建对象和Spring容器创建对象的区别
首先,需要创建实体类Student
package com.itheima.pojo;
public class Student {
private String name;
private int age;
public Student() {
System.out.println("学生的无参构造方法执行");
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
第一种情况,自己创建对象
package com.itheima.test;
import com.itheima.pojo.Student;
import org.junit.Test;
public class MyTest {
@Test
public void test01(){
//第一种情况,自己创建对象
Student stu = new Student();
System.out.println(stu);
}
}
第二种情况,由Spring容器来创建对象
第一步,首先在Spring配置文件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">
<!--创建学生对象
等同于 Student stu = new Student();
id是创建对象的名称 、
class是要创建对象的类型,底层通过反射构建对象-->
<bean id="stu" class="com.itheima.pojo.Student"></bean>
</beans>
第二步,在测试方法中首先创建Spring容器并启动,然后再从Spring容器中获取创建好的bean对象
@Test
public void test02(){
//由Spring容器创建对象
//如果想从Spring容器中取出对象,首先需要创建容器对象,并启动
//启动Spring容器的同时就会创建stu对象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//取出容器中的对象
//调用getBean()方法
Student stu = (Student) ac.getBean("stu");
System.out.println(stu);
}
运行结果