springboot构建

maven构建

以下两种方式任选其一即可

  1. 继承 Starter Parent POM

    1
    2
    3
    4
    5
    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.18</version>
    </parent>
  2. 在没有Parent POM 的情况下使用 Spring Boot

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <dependencyManagement>
    <dependencies>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.7.18</version>
    <type>pom</type>
    <scope>import</scope>
    </dependency>
    </dependencies>
    </dependencyManagement>

引入一个starter,以web为例

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

编写测试代码

1
2
3
4
5
6
7
8
@RestController
public class TestController {

@GetMapping
public String hello() {
return "Hello World";
}
}

使用@SpringBootApplication注解

  1. @SpringBootApplication是3个注解的合集
    1.1 @EnableAutoConfiguration:启用Spring Boot的自动配置
    1.2 @ComponentScan:扫描Bean
    1.3 @SpringBootConfiguration:允许在上下文中注册额外的 bean 或导入其他配置类。

  2. @SpringBootApplication会自动扫描当前包和子包的Bean

1
2
3
4
5
6
7
@SpringBootApplication
public class MyApplication {

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

启动

  1. 运行main方法
  2. curl http://localhost:8080

    Hello World

创建可执行 Jar

maven引入插件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

运行mvn package可以在target目录下得到一个jar