一.环境搭建
新建一个普通Maven项目,删除src文件夹,作为父工程,修改pom.xml
导入依赖:前往https://mvnrepository.com/搜索Spring依赖,选择Spring Web MVC依赖会帮助我们自动导入其他相关依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
二.第一个Spring程序
新建一个子工程Module,spring-01-hellospring,如图建立一个实体类Hello和一个XML文件
package com.bandit.pojo;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
XML文件格式我们可以去官方文档拷贝:https://docs.spring.io/spring-framework/docs/5.3.10-SNAPSHOT/reference/html
改写成我们自己的类
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.bandit.pojo.Hello">
<property name="str" value="Hello Spring"/>
</bean>
</beans>
在官方文档中是用ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
来连接xml与实体类的
编写测试类
@Test
public void Test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
输出: