微服务

SpringBoot基础 | 第一章 - 快速搭建Web应用

2019-01-21  本文已影响8人  学好该死的程序

环境

JDK1.8
Maven

工具

IntelliJ IDEA

操作步骤

一、添加依赖

编辑 pom.xml 文件

<modelVersion>4.0.0</modelVersion>
<groupId>com.msf.tutorial</groupId>
<artifactId>spring-boot-01</artifactId>
<version>1.0-SNAPSHOT</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.5.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
二、添加 SpringBoot 启动类

创建 Application 类,内容如下

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
三、添加 Controller

创建 HelloController 类,内容如下

@RestController
public class HelloController {

    @RequestMapping("/")
    public String sayHello(String name) {
        return "Hello " + name;
    }

}
四、本地运行项目

有多种方式可以本地运行 SpringBoot 项目

方法一、run as Application

直接运行 Application 类的 main 方法

方法二、执行命令 mvn spring-boot:run

五、项目打包,生成可执行的 jar

在 pom 的 build 元素内加上 spring-boot-maven-plugin 插件

<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
</plugins>

执行 maven 打包,在 target 目录下会生成 spring-boot-01-1.0-SNAPSHOT.jar 文件

mvn package

通过 jar 文件运行项目

java -jar target/spring-boot-01-1.0-SNAPSHOT.jar
上一篇 下一篇

猜你喜欢

热点阅读