SpringBoot01-hello world

133 阅读1分钟

内置很多配置,让Java EE开发更加简单,项目可以独立运行,无需额外依赖web容器 (内置了web容器) 官网

添加依赖

在 pom.xml 中添加依赖

<parent>
    <artifactId>spring-boot-starter-parent</artifactId>
    <groupId>org.springframework.boot</groupId>
    <version>2.3.4.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

hello world

创建 Application 类

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

创建 TestController 类

@RestController
public class TestController {
    @GetMapping("/test")
    public String test() {
        return "hello SpringBoot!";
    }
}

image.png

@SpringBootApplication

包含3个注解 可以自己点进去看看 download source

image.png

SpringBoot 2.2.1开始,被SpringBoot扫描到的@Component都不用再加@Configuration

可运行jar

如果希望 mvn package 打包出一个可运行的jar 需要一个插件

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

我 maven 似乎安装不上 不过没事 不重要

热部署

增加依赖 (Debug 模式下,它可以监控classpath的变化)

<!-- 热部署 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>
  • 重新编译项目(2种方式)

手动编译(Build Project、Build Module)这样classpath才有变化

image.png

刷新一波 image.png

自动编译 (不推荐)

image.png

Mac电脑 按 shift + option(Alt) + command + / Windows电脑 按 Shift + Ctrl + Alt + /

image.png

image.png