Skip to content

SpringBoot 入门与起步依赖

TIP

SpringBoot 通过自动配置和起步依赖简化了 Spring 应用的搭建和开发,让开发者可以快速创建一个独立运行的微服务。

SpringBoot 核心特点

  • 独立运行:内嵌 Tomcat/Jetty,直接 java -jar 启动
  • 简化配置:自动配置(Auto Configuration)
  • 起步依赖:按需引入,自动管理版本
  • 生产就绪:Actuator、健康检查、指标监控

快速创建项目

java
// SpringBoot 启动类
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

起步依赖

xml
<!-- 最常用的起步依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

应用入口注解解析

java
@SpringBootApplication // 包含以下三个注解
@EnableAutoConfiguration  // 启动自动配置
@ComponentScan            // 扫描 @Component 等注解
@Configuration            // 标记为配置类

// 等价写法
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.example")
public class Application { }

内嵌容器配置

yaml
# application.yml
server:
  port: 8080
  servlet:
    context-path: /api
  tomcat:
    max-threads: 200
    max-connections: 10000
    uri-encoding: UTF-8