SpringBoot

SpringBoot

Spring Boot 简介

由来

随着动态语言(Ruby、Groovy、Scala、Node.js)的流行,Java 的开发显得格外笨重:繁多的配置、低下的开发效率、复杂的部署流程以及第三方技术集成难度大。在此背景下,Spring Boot 应运而生。它使用”习惯优于配置”(Convention Over Configuration)的理念让项目快速运行起来——项目中存在大量的默认配置,让你无须手动进行配置。

使用 Spring Boot 可以很容易地创建一个独立运行(运行 jar,内嵌 Servlet 容器)、准生产级别的基于 Spring 框架的项目,你可以不用或者只需要很少的 Spring 配置。

优缺点

  • 优点

    • 快速构建项目。
    • 对主流开发框架的无配置集成。
    • 项目可独立运行,无须外部依赖 Servlet 容器。
    • 提供运行时的应用监控。
    • 极大地提高了开发、部署效率。
    • 与云计算的天然集成。
  • 缺点

    • 版本迭代速度快,一些模块改动很大。
    • 由于不用自己做配置,报错时很难定位。

核心功能

  • 独立运行的 Spring 项目

    Spring Boot 可以以 jar 包形式独立运行,只需通过 java -jar xx.jar 即可启动。

  • 内嵌 Servlet 容器

    可选择内嵌 Tomcat、Jetty 或 Undertow,无需以 war 包形式部署。

  • 提供 starter 简化 Maven 配置

    Spring Boot 提供了一系列的 starter pom 来简化依赖管理。

  • 自动配置 Spring

    Spring Boot 会根据类路径中的 jar 包、类,自动配置 Bean,极大减少配置量。若需自定义,可覆盖自动配置。

  • 准生产的应用监控

    提供基于 HTTP、SSH、Telnet 对运行时的项目进行监控(Actuator)。

  • 无代码生成和 XML 配置

    通过条件注解实现,完全使用 Java 配置和注解,无需任何 XML。

  • 与云计算的天然集成

    方便部署到云平台。

Spring Boot 基础

配置文件

Spring Boot 支持两种格式的配置文件:application.properties​ 和 application.yml(YAML 格式更简洁)。

  • 配置文件优先级

    配置文件按优先级从高到低加载,高优先级会覆盖低优先级配置:

    • file:./config/ (项目根目录下的 config 文件夹)
    • file:./ (项目根目录)
    • classpath:/config/ (resources 目录下的 config 文件夹)
    • classpath:/ (resources 目录)
  • YAML 基本语法

    1
    2
    3
    4
    person:
    name: SLy
    age: 13
    sex: boy
  • 读取配置文件

    • 使用 @ConfigurationProperties 批量绑定

      1
      2
      3
      4
      5
      6
      7
      8
      9
      @Component
      @ConfigurationProperties(prefix = "person")
      // @PropertySource(value = "classpath:custom.properties") // 可指定额外配置文件
      public class Person {
      private String name;
      private Integer age;
      private String sex;
      // getters and setters
      }
    • 使用 @Value 单个注入

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      @Component
      public class Person {
      @Value("${person.name}")
      private String name;
      @Value("${person.age}")
      private Integer age;
      @Value("${person.sex}")
      private String sex;
      // getters and setters
      }
    • 区别

      • @ConfigurationProperties 支持批量注入、复杂类型(如 List、Map),并且支持 JSR-303 数据校验。
      • @Value 支持 SpEL 表达式,适合单个值的注入。
  • 多环境配置

    • 方式一:多个配置文件

      • application-dev.yml(开发环境)
      • application-test.yml(测试环境)
      • application-prod.yml(生产环境)

      application.yml 中指定激活的环境:

      1
      2
      3
      spring:
      profiles:
      active: dev
    • 方式二:单个 YAML 多文档块

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      spring:
      profiles:
      active: test
      ---
      spring:
      profiles: dev
      server:
      port: 8080
      ---
      spring:
      profiles: test
      server:
      port: 8081
      ---
      spring:
      profiles: prod
      server:
      port: 8082

日志

Spring Boot 使用 Commons Logging 记录内部日志,但开放底层实现。默认使用 Logback,并提供对 Java Util Logging、Log4J2 的支持。

  • 日志格式

    默认输出格式包含:

    • 日期和时间(毫秒精度)
    • 日志级别:ERROR, WARN, INFO, DEBUG, TRACE
    • 进程 ID
    • — 分隔符
    • 线程名称(方括号中)
    • 日志记录器名称(通常为源类名的缩写)
    • 日志内容

    Logback 没有 FATAL 级别,对应 ERROR。

  • 日志文件输出

    默认只输出到控制台。如需输出到文件,设置以下属性:

    • logging.file=my.log(指定文件名,可绝对路径或相对路径)
    • logging.path=/var/log(指定目录,生成 spring.log 文件)

    日志文件达到 10MB 时会轮转,可通过 logging.file.max-size​ 修改大小限制,轮转文件保留时间通过 logging.file.max-history 控制。

  • 日志级别

    配置方式:

    1
    2
    3
    logging.level.root=WARN
    logging.level.org.springframework.web=DEBUG
    logging.level.org.hibernate=ERROR
  • 自定义日志配置

    在 classpath 下放置对应日志框架的配置文件(如 logback-spring.xml​),并通过 logging.config​ 指定位置。建议使用 -spring​ 后缀(如 logback-spring.xml),以便 Spring Boot 完全控制初始化。

    日志框架与配置文件对应关系:

    日志系统 配置文件
    Logback logback-spring.xml, logback-spring.groovy, logback.xml
    Log4j2 log4j2-spring.xml, log4j2.xml
    JDK (Java Util Logging) logging.properties
  • Logback 扩展

    Spring Boot 为 Logback 提供了一些扩展功能,可在 logback-spring.xml​ 中使用 <springProfile> 标签实现环境相关的配置。

事务

当引入 spring-boot-starter-jdbc​ 或 spring-boot-starter-data-jpa​ 时,Spring Boot 会自动配置事务管理器(DataSourceTransactionManager 或 JpaTransactionManager)。使用时只需在方法或类上添加 @Transactional 注解。

1
2
3
4
5
6
7
@Service
public class UserService {
@Transactional
public void updateUser() {
// 数据库操作
}
}

@Transactional 可注解在类上,表示该类的所有 public 方法都开启事务。若类和方法同时注解,方法上的注解会覆盖类上的配置。

Spring Boot 核心注解详解

@SpringBootApplication

这是一个复合注解,包含以下三个核心注解:

  • @Configuration:标明该类为配置类。
  • @EnableAutoConfiguration:开启自动配置。
  • @ComponentScan:启用组件扫描。

因此,启动类可直接写为:

1
2
3
4
5
6
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

等价于:

1
2
3
4
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class DemoApplication { ... }

@Configuration 与 @Bean

@Configuration​ 标注的类相当于 XML 配置文件,其中的 @Bean​ 方法会向容器注册 bean。@Configuration​ 类本身会被 CGLIB 动态代理,确保 @Bean 方法返回的单例对象唯一。

1
2
3
4
5
6
7
@Configuration
public class MyConfig {
@Bean
public UserService userService() {
return new UserService();
}
}

@Configuration​ 与 @Component 的区别:

  • @Configuration​ 中的 @Bean 方法会被 CGLIB 代理,调用该方法返回的是同一个实例(单例)。
  • @Component​ 中的 @Bean​ 方法不会被代理,每次调用都会新建一个实例。因此,若在 @Component​ 中定义了 @Bean​ 方法且需要引用另一个 @Bean,应通过依赖注入而不是直接方法调用。

@EnableAutoConfiguration

该注解借助 @Import(AutoConfigurationImportSelector.class)​ 将所有符合条件的自动配置类加载到 IoC 容器。AutoConfigurationImportSelector 通过 SpringFactoriesLoader 加载 META-INF/spring.factories 中配置的自动配置类。

@ComponentScan

自动扫描指定包下的组件(如 @Component​, @Service​, @Repository​, @Controller 等)。默认扫描启动类所在包及其子包。

@Component 与 @Configuration 的代理区别

@Configuration​ 类会被 CGLIB 增强,从而拦截 @Bean​ 方法的调用,确保返回单例。而 @Component​ 不会,因此如果希望避免代理(例如在有些测试场景),可以使用 @Component​ 替代 @Configuration​,但此时需要手动处理依赖(通过 @Autowired​ 注入其他 @Bean)。

@PropertySource 与属性绑定

  • @PropertySource​ 用于加载指定的配置文件(如 classpath:custom.properties)。
  • @ConfigurationProperties 将配置文件中的属性绑定到 Java Bean。
  • @Value 用于单个属性注入,支持 SpEL。

示例:

1
2
3
4
5
6
7
8
@PropertySource("classpath:user.properties")
@Component
@ConfigurationProperties(prefix = "user")
public class User {
private String name;
private Integer age;
// getters/setters
}

自动配置原理深入

SpringFactoriesLoader

Spring Boot 使用 SpringFactoriesLoader 从 META-INF/spring.factories 文件中加载配置。它是一个类似 Java SPI 的扩展机制。spring.factories 文件内容格式为 key=value,其中 value 为多个逗号分隔的类名。

对于自动配置,key 为 org.springframework.boot.autoconfigure.EnableAutoConfiguration,value 为一系列自动配置类的全限定名。

@EnableAutoConfiguration 加载过程

  • @EnableAutoConfiguration​ 通过 @Import(AutoConfigurationImportSelector.class) 导入选择器。
  • AutoConfigurationImportSelector.selectImports() 调用 SpringFactoriesLoader.loadFactoryNames() 获取 EnableAutoConfiguration 对应的所有自动配置类名。
  • 去重、排除不需要的类,然后经过条件过滤(如 @Conditional 注解),最终将满足条件的自动配置类注册到容器。

自动配置类与属性绑定

每个自动配置类(如 ServletWebServerFactoryAutoConfiguration)通常配合一个 XxxProperties 类(如 ServerProperties)使用。XxxProperties 通过 @ConfigurationProperties​ 与配置文件中的属性绑定,并通过 @EnableConfigurationProperties 注册到容器。自动配置类会从这些 Properties 中获取配置来创建相应的 Bean。

示例(简化):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@ConfigurationProperties(prefix = "server")
public class ServerProperties {
private int port = 8080;
// getter/setter
}

@Configuration
@EnableConfigurationProperties(ServerProperties.class)
public class ServletWebServerFactoryAutoConfiguration {
@Bean
public TomcatServletWebServerFactory tomcatFactory(ServerProperties serverProperties) {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.setPort(serverProperties.getPort());
return factory;
}
}

条件注解

Spring Boot 提供了一系列 @Conditional 派生注解,用于控制自动配置是否生效。常见的有:

  • @ConditionalOnBean:容器中存在指定的 Bean 时生效。
  • @ConditionalOnMissingBean:容器中不存在指定的 Bean 时生效。
  • @ConditionalOnClass:类路径下存在指定的类时生效。
  • @ConditionalOnMissingClass:类路径下不存在指定的类时生效。
  • @ConditionalOnProperty:指定的配置属性具有特定值时生效(如 matchIfMissing 可设置属性不存在时是否匹配)。
  • @ConditionalOnWebApplication:当前应用是 Web 应用时生效。
  • @ConditionalOnNotWebApplication:当前应用不是 Web 应用时生效。
  • @ConditionalOnExpression:根据 SpEL 表达式结果决定。

调整自动配置顺序

使用 @AutoConfigureBefore​、@AutoConfigureAfter​、@AutoConfigureOrder 可以调整自动配置类的加载顺序,确保依赖关系正确。

例如:

1
2
3
4
5
@Configuration
@AutoConfigureAfter(JmxAutoConfiguration.class)
public class AfterMBeanServerReadyConfiguration {
// ...
}

Spring Boot Starter 详解

Starter 概念

Starter 是一组依赖描述,用于简化项目的依赖管理。通过引入一个 starter,可以一站式获得该场景所需的所有依赖,并自动配置相关功能。Starter 命名通常为 spring-boot-starter-*

常用 Starter 列表

以下为常见 Starter 及其作用(基于 Spring Boot 2.x):

Starter 名称 描述
spring-boot-starter 核心 starter,包括自动配置支持、日志和 YAML 解析
spring-boot-starter-web 构建 Web 应用(包括 RESTful),默认使用 Tomcat
spring-boot-starter-test 测试相关,包括 JUnit、Hamcrest、Mockito
spring-boot-starter-data-jpa 使用 Spring Data JPA 与 Hibernate
spring-boot-starter-jdbc 使用 JDBC 与 Tomcat JDBC 连接池
spring-boot-starter-security 使用 Spring Security
spring-boot-starter-actuator 提供生产就绪功能,如监控和管理端点
spring-boot-starter-aop 使用 Spring AOP 和 AspectJ 实现面向切面编程
spring-boot-starter-logging 使用 Logback 进行日志记录(默认)
spring-boot-starter-log4j2 使用 Log4j2 进行日志记录
spring-boot-starter-thymeleaf 使用 Thymeleaf 视图构建 MVC Web 应用
spring-boot-starter-data-redis 使用 Redis 和 Spring Data Redis
spring-boot-starter-amqp 使用 Spring AMQP 和 RabbitMQ
spring-boot-starter-websocket 使用 WebSocket 构建应用
spring-boot-starter-mail 邮件发送支持
spring-boot-starter-cache 缓存抽象支持
spring-boot-starter-validation 使用 Java Bean Validation 进行参数校验

spring-boot-starter-logging

默认日志 starter,自动使用 Logback 作为日志框架。可通过 logging.*​ 配置或提供自定义的 logback-spring.xml 进行调整。

spring-boot-starter-web

提供 Web 开发所需依赖(Spring MVC、内嵌 Tomcat 等),并自动配置:

  • 必要的 ViewResolver(如 ContentNegotiatingViewResolver)。
  • 静态资源映射(/static、/public、/resources、/META-INF/resources)。
  • HttpMessageConverter 支持 JSON、XML 等。
  • 其他 Web 相关组件。

项目结构约定:

  • 静态资源(css、js 等)放在 src/main/resources/static
  • 模板文件放在 src/main/resources/templates

定制 Spring MVC:

  • 实现 WebMvcConfigurer 接口来添加自定义配置,如拦截器、视图控制器等。
  • 若需完全接管 Spring MVC,可在配置类上添加 @EnableWebMvc

spring-boot-starter-jdbc

提供数据访问基础支持,自动配置 DataSource、JdbcTemplate、DataSourceTransactionManager。如果未配置 DataSource,Spring Boot 会使用嵌入式数据库(H2、HSQL、Derby)。可通过 spring.datasource.* 配置数据库连接。

多数据源问题:
当配置多个 DataSource Bean 时,Spring Boot 的自动配置可能失效。解决方法:

  • 排除 DataSourceAutoConfiguration 和 DataSourceTransactionManagerAutoConfiguration。
  • 或使用 @Primary 标注其中一个数据源。

spring-boot-starter-aop

引入 Spring AOP 和 AspectJ 支持,自动开启 @EnableAspectJAutoProxy​。可通过 spring.aop.auto​ 和 spring.aop.proxy-target-class 控制。

spring-boot-starter-security

为 Web 应用添加安全防护,默认启用 HTTP Basic 认证,用户名为 user,密码在启动时随机生成打印在控制台。可通过 spring.security.user.name​ 和 spring.security.user.password 自定义。

定制 Spring Security:

  • 继承 WebSecurityConfigurerAdapter 并配合 @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)​ 重写 configure(HttpSecurity http) 等方法。
  • 完全自定义:实现 @EnableWebSecurity 的配置类,手动配置认证管理器、访问决策管理器等。

spring-boot-starter-actuator

提供生产级监控功能,包括一系列端点(Endpoint),分为传感器(Sensor)和执行器(Actuator)两类。

常用端点:

端点 ID 描述
autoconfig 自动配置报告
beans 容器中所有 Bean 的信息
configprops 配置属性报告(已消毒)
env 环境属性
health 健康状态
info 应用信息(可自定义)
metrics 度量指标
mappings 请求映射
trace 请求追踪信息
shutdown 关闭应用(默认关闭)

自定义健康检查:
实现 HealthIndicator 接口(或继承 AbstractHealthIndicator),并注册为 Bean。例如检查 Dubbo 服务:

1
2
3
4
5
6
7
public class DubboHealthIndicator extends AbstractHealthIndicator {
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
// 执行健康检查逻辑
builder.up().withDetail("dubbo", "OK");
}
}

暴露端点:

  • 通过 JMX:所有端点自动暴露为 MBean。
  • 通过 HTTP:可配置 management.endpoints.web.exposure.include 指定暴露的端点,默认只暴露 health 和 info。

Web 应用开发

整合 Servlet / Filter / Listener

  • 方式一:注解扫描(推荐)

    • 在 Servlet、Filter、Listener 上使用 @WebServlet​、@WebFilter​、@WebListener
    • 在启动类上添加 @ServletComponentScan 注解。

    示例:

    1
    2
    3
    4
    5
    6
    @WebServlet("/myServlet")
    public class MyServlet extends HttpServlet { ... }

    @SpringBootApplication
    @ServletComponentScan
    public class App { ... }
  • 方式二:注册 Bean

    使用 ServletRegistrationBean、FilterRegistrationBean、ServletListenerRegistrationBean 注册。

    1
    2
    3
    4
    5
    6
    @Bean
    public ServletRegistrationBean<MyServlet> servletRegistrationBean() {
    ServletRegistrationBean<MyServlet> bean = new ServletRegistrationBean<>(new MyServlet());
    bean.addUrlMappings("/myServlet");
    return bean;
    }

静态资源配置

默认静态资源路径(按优先级):

  • classpath:/META-INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public/

可通过 spring.resources.static-locations​ 自定义。
此外,支持 WebJars:将静态资源打包成 JAR,放在 classpath:/META-INF/resources/webjars/​,可通过 /webjars/** 访问。

Spring MVC 自动配置与扩展

Spring Boot 为 Spring MVC 提供了大量自动配置,包括:

  • ContentNegotiatingViewResolver 和 BeanNameViewResolver
  • 静态资源支持
  • 自动注册 Converter、GenericConverter、Formatter
  • HttpMessageConverter 支持
  • MessageCodesResolver(错误码生成)
  • 静态 index.html 作为欢迎页
  • 自定义 Favicon

扩展 Spring MVC:
实现 WebMvcConfigurer 接口,在配置类中重写相关方法。

1
2
3
4
5
6
7
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/hello").setViewName("hello");
}
}

完全控制 Spring MVC:
在配置类上添加 @EnableWebMvc,此时 Spring Boot 的自动配置将失效,需自己配置所有 MVC 组件。

文件上传与下载

Spring Boot 通过 MultipartAutoConfiguration 自动配置文件上传功能。只需在 Controller 方法中使用 MultipartFile 接收文件。

1
2
3
4
5
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) {
// 保存文件
return "success";
}

配置文件上传相关属性:

1
2
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

全局异常处理

使用 @ControllerAdvice​ 和 @ExceptionHandler 统一处理异常。

1
2
3
4
5
6
7
8
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public String handleException(Exception e) {
return "error: " + e.getMessage();
}
}

跨域配置(CORS)

可通过实现 WebMvcConfigurer 的 addCorsMappings 方法全局配置 CORS。

1
2
3
4
5
6
7
8
9
10
11
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowCredentials(true)
.maxAge(3600);
}
}

或者在 Controller 或方法上使用 @CrossOrigin 注解。

国际化(i18n)

Spring Boot 支持通过 MessageSource 实现国际化。在 application.properties 中配置:

1
2
spring.messages.basename=messages
spring.messages.encoding=UTF-8

在 resources 下创建 messages.properties(默认)、messages_en_US.properties、messages_zh_CN.properties 等文件。在代码中使用 MessageSource 获取消息,或使用 #{…} 表达式在模板中引用。

数据访问与持久化

JDBC 与 JdbcTemplate

引入 spring-boot-starter-jdbc 后,可直接注入 JdbcTemplate 使用。

1
2
3
4
5
6
7
8
9
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;

public List<User> findAll() {
return jdbcTemplate.query("select * from user", new BeanPropertyRowMapper<>(User.class));
}
}

Spring Data JPA

引入 spring-boot-starter-data-jpa​,配置 spring.datasource.*​ 和 JPA 相关属性(如 spring.jpa.hibernate.ddl-auto)。定义实体和 Repository 接口即可。

1
2
3
4
5
6
7
8
9
10
11
@Entity
public class User {
@Id @GeneratedValue
private Long id;
private String name;
// getters/setters
}

public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByName(String name);
}

多数据源配置

配置多个 DataSource 时,需手动创建对应的 SqlSessionFactory、TransactionManager 等,并排除自动配置。示例(两个数据源):

1
2
3
4
5
6
7
8
9
10
11
@Configuration
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties("spring.datasource.primary")
public DataSource primaryDataSource() { ... }

@Bean
@ConfigurationProperties("spring.datasource.secondary")
public DataSource secondaryDataSource() { ... }
}

并分别为每个数据源配置 JdbcTemplate 或 EntityManagerFactory。

事务管理深入

@Transactional 支持多种属性:

  • propagation:事务传播行为(REQUIRED、REQUIRES_NEW 等)。
  • isolation:事务隔离级别(READ_COMMITTED 等)。
  • timeout:超时时间。
  • rollbackFor:指定触发回滚的异常类。
  • noRollbackFor:指定不触发回滚的异常类。

缓存

Spring Boot 提供缓存抽象,通过 @EnableCaching​ 开启,使用 @Cacheable​、@CachePut​、@CacheEvict 等注解。

整合 Redis 作为缓存:
引入 spring-boot-starter-data-redis​ 和 spring-boot-starter-cache,并在在配置中启用:

1
2
3
4
5
6
7
8
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
return RedisCacheManager.create(factory);
}
}

NoSQL 集成

  • Redis:使用 RedisTemplate 操作。

    1
    2
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
  • MongoDB:引入 spring-boot-starter-data-mongodb,定义 MongoRepository 接口。

    1
    public interface UserRepository extends MongoRepository<User, String> { ... }

消息与任务调度

JMS(ActiveMQ/Artemis)

引入对应 starter(如 spring-boot-starter-activemq​),配置连接信息,使用 JmsTemplate 发送消息,@JmsListener 接收消息。

RabbitMQ

引入 spring-boot-starter-amqp​,配置 spring.rabbitmq.*​,使用 RabbitTemplate 发送消息,@RabbitListener 接收消息。

Kafka

引入 spring-boot-starter-kafka​,配置 spring.kafka.*​,使用 KafkaTemplate 发送消息,@KafkaListener 接收消息。

定时任务(@Scheduled)

在启动类上添加 @EnableScheduling​,然后在方法上使用 @Scheduled(cron = "0 * * * * ?") 或固定延迟 fixedDelay。

1
2
3
4
5
6
7
@Component
public class ScheduledTasks {
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("现在时间:" + new Date());
}
}

异步任务(@Async)

在启动类上添加 @EnableAsync​,然后在需要异步执行的方法上使用 @Async。可自定义线程池配置。

1
2
3
4
5
6
7
8
@Component
public class AsyncTasks {
@Async
public Future<String> doTask() throws InterruptedException {
// 长时间任务
return new AsyncResult<>("任务完成");
}
}

安全与监控

Spring Security 基础

Spring Security 的核心概念:

  • AuthenticationManager:负责认证。
  • AccessDecisionManager:负责授权。
  • SecurityInterceptor:拦截请求,执行认证和授权。

自定义用户认证:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}123456").roles("ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin().permitAll();
}
}

Actuator 端点详解

除了标准端点,还可以自定义端点:

1
2
3
4
5
6
7
8
@Component
@Endpoint(id = "custom")
public class CustomEndpoint {
@ReadOperation
public String custom() {
return "custom data";
}
}

健康检查聚合:多个 HealthIndicator 会聚合成一个整体健康状态,可通过 HealthAggregator 自定义聚合逻辑。

度量指标(Metrics):Spring Boot 提供 MeterRegistry 注册自定义指标,支持多种监控系统(Prometheus、InfluxDB 等)。

测试

集成测试 @SpringBootTest

@SpringBootTest 会启动完整的应用上下文,可用于集成测试。

1
2
3
4
5
6
7
8
9
10
@SpringBootTest
class ApplicationTests {
@Autowired
private UserService userService;

@Test
void testUser() {
// ...
}
}

Web 层测试 @WebMvcTest

仅加载 Web 层相关组件,可配合 @MockBean 模拟 Service 层。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;

@MockBean
private UserService userService;

@Test
void testGetUser() throws Exception {
mockMvc.perform(get("/user/1"))
.andExpect(status().isOk());
}
}

数据层测试 @DataJpaTest

仅加载 JPA 相关组件,默认使用嵌入式数据库,事务回滚。

1
2
3
4
5
6
7
8
9
10
@DataJpaTest
class UserRepositoryTest {
@Autowired
private UserRepository userRepository;

@Test
void testFindByName() {
// ...
}
}

测试切片与 Mock

Spring Boot 提供了一系列测试切片注解,如 @JsonTest​、@RestClientTest 等,用于聚焦特定模块测试。

部署与发布

可执行 jar 打包与运行

使用 spring-boot-maven-plugin 打包:

1
2
3
4
5
6
7
8
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

运行 mvn package​ 生成可执行 jar,通过 java -jar xxx.jar 启动。

RPM 部署

通过编写 .spec 文件,将可执行 jar、配置、脚本打包成 RPM,便于在 CentOS/RHEL 上使用 yum 管理。构建工具可使用 rpm-maven-plugin 或外部 rpmbuild。

Docker 部署

编写 Dockerfile:

1
2
3
4
FROM openjdk:8-jre-alpine
COPY target/app.jar /app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app.jar"]

构建镜像:docker build -t myapp .
运行容器:docker run -p 8080:8080 myapp

在微服务架构中,常结合 CI/CD 流水线实现自动化部署。

开发效率提升

Spring Boot DevTools

DevTools 提供:

  • 自动重启:当 classpath 中的文件变化时,自动重启应用(比手动重启快)。
  • LiveReload:内嵌 LiveReload 服务器,资源变化时触发浏览器刷新。
  • 远程调试:支持远程应用的热更新。

引入依赖:

1
2
3
4
5
6
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>

Spring Boot 配置处理器

生成配置元数据,方便 IDE 提示:

1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

编译时会生成 META-INF/spring-configuration-metadata.json

附录:Spring Boot 2.x 新特性

  • 基于 Spring 5:支持响应式编程(WebFlux)。
  • 配置属性迁移:许多属性名发生变化(如 server.servlet.path​ 替代 server.servlet-path)。
  • 内嵌容器包结构调整:spring-boot-starter-tomcat 不再默认提供 JSP 支持,需额外添加依赖。
  • Actuator 端点重新设计:基础路径改为 /actuator,端点 ID 统一为小写,安全性增强。
  • 数据源初始化:使用 spring.datasource.initialization-mode 控制初始化(always/embedded/never)。
  • 支持 Java 8 以上,放弃 Java 6/7。
  • 更好的依赖管理:通过 spring-boot-dependencies BOM 管理版本。