创建一个maven项目(具体前面有写)
导入java包,由于我们使用的是maven,因此导入依赖即可
需要导入核心依赖以及日志依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
也可以自己去maven残酷下载不同的版本,尽量使用人多使用的版本
在资源目录下建一个xml文件,名字随意起
在里面进行spring容器的配置
<?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">
<!--id:实例对象的名称,class为类的路径-->
<bean id="student" class="pojo.Student">
<!--为属性赋值-->
<property name="id" value="18"></property>
<property name="name" value="huisheng_qaq"></property>
</bean>
</beans>
这段xml文件可能会由于版本不同而报错
可以在下载的对应的spring版本的文档中复制过来
接下来在新建一个javabean,在pojo包中
package pojo;
public class Student {
private String name;
private Integer id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", id=" + id +
'}';
}
}
在工具类中进行测试
package tool;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.Student;
public class TestStudent {
public static void main(String[] args) {
//通过类加载器获取上下文中的spring容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
//通过容器实例化对象
Student student = (Student) applicationContext.getBean("student");
System.out.println(student);
}
}
运行结果
第一个spring创建成功