原文: https://spring.io/guides/gs/serving-web-content/
附源码:构建一个简单的spring-boot的web项目
目标:
本文目标在于构建一个简单的spring-boot-web项目,了解spring-boot-web项目的基本目录结构、maven依赖、启动流程等内容
1. 初始化源代码
从spring网站初始化和下载源代码
将下载好的源代码作为maven项目导入idea,结构如下
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.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.4.2</version>
</plugin>
</plugins>
</build>
</project>
配置文件:application.properties为空;
源代码:DemoApplication.java文件是spring-boot-web项目启动入口
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name){
return String.format("Hello %s", name);
}
}
注释:
@SpringBootApplication:
@ComponentScan:spring启动时自动扫描spring四大注解类[@Controller,@Service,@Repository,@Component],扫描范围是SpringBootApplication注解所在包及其子包中的类;
@SpringBootConfiguration:声明当前类是一个配置类,配置类中可以使用@Bean注解代理生成Spring管理的Bean,然后在其他位置注入使用这个Bean
@EnableAutoConfiguration:springboot自动化配置核心注解
@RestController = @Controller + @ResponseBody
@Controller:将修饰类注入SpringBoot IOC容器且充当Controller作用,项目跑起来时该类即被实例化
@ResponseBody:该类中所有的API接口返回的数据均以字符串的形式返回给调用端
spring-boot-starter-web项目内嵌tomcat,默认开启web server端口8080
2. 启动DemoApplication
浏览器访问:http://localhost:8080/hello;
浏览器传参:http://localhost:8080/hello?name=xiaoming
3.构建和启动项目
命令行模式下切入项目源代码路径下;
执行命令:
mvnw spring-boot:run
启动后如步骤2访问项目即可