快速构建一个Spring boot基础项目,并实现一个简单的Http请求处理。
编程环境:
java version "1.8.0_171"
Apache Maven 3.5.4
使用IDEA创建一个新项目

下一步

下一步

下一步

自动导入相关依赖

创建包controller和HelloWorldController类

代码如下:
package com.example.helloword.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@RequestMapping("/hello")
public String index() {
return "Hello World";
}
}
运行HellowordApplication,下图已经启动完成


项目搭建完成
接下来慢慢讲解一下spring boot都干了啥
首先看下项目结构:
HellowordApplication:一个自带main方法的类,用于启动程序
HellowordApplicationTests:一个空的测试类
application.properties:一个空的配置文件,可以添加相应的配置属性
pom.xml:Maven 构建文件
应用入口类:HellowordApplication
Spring Boot项目通常会有一个名为*Application的入口类,入口类中有一个main方法,这个main方法就是一个标准的java应用的入口方法。
@SpringBootApplication加在入口类上,是spring boot的核心注解,该注解组合了@Configuration、@EnableAutoConfiguration、@ComponentScan;可以使用这三个注解代替它
- 其中@EnableAutoConfiguration让spring boot 根据类路径上的jar包依赖为当前项目进行自动配置,例如,添加了spring-boot-starter-web依赖,会自动添加Tomcat和Spring MVC的依赖,此时spring boot会对Tomcat和Spring MVC进行自动配置。
- @ComponentScan让spring boot自动扫描入口类的同级包以及下级包里的Bean
附件: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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>helloword</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>helloword</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<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>
</plugin>
</plugins>
</build>
</project>
网友评论