SpringBoot
新建项目
项目文件结构
@SpringBootApplication
public class SpringBootTestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootTestApplication.class, args);
}
}
@SpringBootTest
class SpringBootTestApplicationTests {
@Test
void contextLoads() {
}
}
我们在创建SpringBoot项目之后,首先会自动生成一个主类,而主类中的main
方法中调用了SpringApplication
类的静态方法来启动整个SpringBoot项目,并且我们可以看到主类的上方有一个@SpringBootApplication
注解
同时还自带了一个测试类,测试类的上方仅添加了一个@SpringBootTest
注解
@SpringBootApplication
注解中自动触发包扫描
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 父工程-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/> <!-- 从存储库中查找父类 -->
</parent>
<groupId>com.example</groupId>
<artifactId>springboot-study</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBootTest</name>
<description>SpringBootTest</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- spring-boot-starter SpringBoot核心启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- spring-boot-starter-test SpringBoot测试模块启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!-- SpringBoot Maven插件,打包Jar -->
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
整合Web相关框架
SpringBoot内嵌了一个Tomcat服务器,也就是说打包成jar包之后,相当于就是一个可以直接运行的应用程序
新建SpringBootWeb项目
由于SpringBoot是自动扫描的,因此我们直接创建一个Controller即可被加载:
它还可以自动识别类型,如果我们返回的是一个对象类型的数据,那么它会自动转换为JSON数据格式,无需配置:
@Data
@Component
public class Student {
String name;
String sex;
int sid;
}
@RequestMapping("/student")
@ResponseBody
public Student student(){
Student student = new Student();
student.setName("小明");
student.setSex("男");
student.setSid(10);
return student;
}
响应了一个json数据
修改Web相关配置
# 修改端口为80
server.port=80
自定义的配置项,并在我们的项目中通过@Value
直接注入:
test.name = Hello world!
@Value("${test.name}")
String name;