Spring Boot 注解大全:全面解析与实战应用

发布于:2025-03-13 ⋅ 阅读:(15) ⋅ 点赞:(0)

目录

一、Spring Boot 启动与配置相关注解

1.1 @SpringBootApplication

1.2 @EnableAutoConfiguration

1.3 @Configuration

1.4 @ComponentScan

二、依赖注入与组件管理注解

2.1 @Component

2.2 @Service

2.3 @Repository

2.4 @Controller

2.5 @RestController

2.6 @Autowired

2.7 @Qualifier

2.8 @Resource

2.9 @Value

三、Web 开发相关注解

3.1 @RequestMapping

3.2 @GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping

3.3 @PathVariable

3.4 @RequestParam

3.5 @RequestBody

3.6 @RequestHeader

3.7 @CookieValue

3.8 @ModelAttribute

3.9 @SessionAttributes

四、数据访问与事务管理注解

4.1 @Entity

4.2 @Table

4.3 @Id

4.4 @GeneratedValue

4.5 @Column

4.6 @Repository

4.7 @Transactional

五、AOP 相关注解

5.1 @Aspect

5.2 @Pointcut

5.3 @Before

5.4 @After

5.5 @AfterReturning

5.6 @AfterThrowing

5.7 @Around

六、测试相关注解

6.1 @SpringBootTest

6.2 @MockBean

6.3 @WebMvcTest

6.4 @DataJpaTest

七、其他注解

7.1 @Conditional

7.2 @ConditionalOnClass

7.3 @ConditionalOnMissingBean

7.4 @ConditionalOnProperty

7.5 @Scheduled

7.6 @EnableScheduling

7.7 @EnableAsync

7.8 @Async

7.9 @ConfigurationProperties

7.10 @EnableConfigurationProperties


一、Spring Boot 启动与配置相关注解

1.1 @SpringBootApplication

这是 Spring Boot 应用中最核心的注解,通常位于主应用类上。它是一个组合注解,实际上包含了 @Configuration@EnableAutoConfiguration 和 @ComponentScan 三个注解的功能。

  • 作用
    • @Configuration:表明该类是一个配置类,相当于传统 Spring 中的 XML 配置文件。
    • @EnableAutoConfiguration:开启 Spring Boot 的自动配置功能,Spring Boot 会根据类路径下的依赖和配置自动配置应用。
    • @ComponentScan:指定 Spring 扫描组件的范围,默认扫描主应用类所在包及其子包下带有 @Component@Service@Repository@Controller 等注解的类。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

1.2 @EnableAutoConfiguration

  • 作用:Spring Boot 会根据类路径中的依赖自动配置应用。例如,如果类路径中存在 H2 数据库的依赖,Spring Boot 会自动配置一个嵌入式的 H2 数据库。不过,有时候自动配置可能不符合我们的需求,这时可以使用 exclude 属性排除某些自动配置类。
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

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

1.3 @Configuration

  • 作用:用于定义配置类,配置类可以包含多个 @Bean 注解的方法,这些方法会返回一个对象,该对象会被 Spring 容器管理。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class AppConfig {
    @Bean
    public List<String> myList() {
        return new ArrayList<>();
    }
}

1.4 @ComponentScan

  • 作用:指定 Spring 扫描组件的范围。可以通过 basePackages 属性指定要扫描的包,也可以通过 basePackageClasses 指定要扫描的类所在的包。
  • 示例
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.example.demo.service")
public class AppConfig {
    // 配置类内容
}

二、依赖注入与组件管理注解

2.1 @Component

  • 作用:这是一个通用的组件注解,用于标记一个类为 Spring 组件,被 Spring 容器管理。它是 @Service@Repository@Controller 的父注解。
  • 示例
import org.springframework.stereotype.Component;

@Component
public class MyComponent {
    public void doSomething() {
        System.out.println("Doing something in MyComponent");
    }
}

2.2 @Service

  • 作用:通常用于标记业务逻辑层的类,是 @Component 的一种特殊形式,语义上更明确表示这是一个服务类。
  • 示例
import org.springframework.stereotype.Service;

@Service
public class UserService {
    public void saveUser() {
        // 保存用户的业务逻辑
    }
}

2.3 @Repository

  • 作用:主要用于标记数据访问层的类,如 DAO 类。Spring 会自动处理 @Repository 注解类抛出的异常,将其转换为 Spring 的数据访问异常。
  • 示例
import org.springframework.stereotype.Repository;

@Repository
public class UserRepository {
    public void saveUserToDb() {
        // 将用户保存到数据库的逻辑
    }
}

2.4 @Controller

  • 作用:用于标记控制器类,处理 HTTP 请求。通常与 @RequestMapping 等注解配合使用。
  • 示例
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {
    @RequestMapping("/hello")
    @ResponseBody
    public String sayHello() {
        return "Hello, World!";
    }
}

2.5 @RestController

  • 作用:是 @Controller 和 @ResponseBody 的组合注解,用于创建 RESTful 风格的控制器,方法返回的对象会自动转换为 JSON 或 XML 等格式返回给客户端。
  • 示例
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyRestController {
    @GetMapping("/data")
    public String getData() {
        return "{\"message\": \"This is some data\"}";
    }
}

2.6 @Autowired

  • 作用:用于自动装配 Bean,默认按照类型进行装配。可以用于构造器、字段、方法上。
  • 示例
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    private UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void saveUser() {
        userRepository.saveUserToDb();
    }
}

2.7 @Qualifier

  • 作用:当存在多个相同类型的 Bean 时,@Autowired 无法确定要注入哪个 Bean,此时可以使用 @Qualifier 指定要注入的 Bean 的名称。
  • 示例
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
public class MyService {
    private MyComponent myComponent;

    @Autowired
    public MyService(@Qualifier("specificComponent") MyComponent myComponent) {
        this.myComponent = myComponent;
    }
}

2.8 @Resource

  • 作用:也是用于依赖注入,默认按照名称进行装配,如果找不到匹配的名称,则按照类型进行装配。
  • 示例
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class MyService {
    @Resource
    private MyComponent myComponent;

    public void doSomething() {
        myComponent.doSomething();
    }
}

2.9 @Value

  • 作用:用于从配置文件中读取属性值并注入到 Bean 的字段中。支持 SpEL 表达式。
  • 示例
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyConfig {
    @Value("${app.name}")
    private String appName;

    public String getAppName() {
        return appName;
    }
}

三、Web 开发相关注解

3.1 @RequestMapping

  • 作用:用于映射 HTTP 请求到控制器的处理方法上。可以指定请求的 URL、请求方法(GET、POST 等)、请求参数等。
  • 示例
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    @ResponseBody
    public String sayHello() {
        return "Hello, World!";
    }
}

3.2 @GetMapping@PostMapping@PutMapping@DeleteMapping@PatchMapping

  • 作用:这些注解是 @RequestMapping 的简化形式,分别对应 HTTP 的 GET、POST、PUT、DELETE、PATCH 请求方法。
  • 示例
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyRestController {
    @GetMapping("/data")
    public String getData() {
        return "{\"message\": \"This is some data\"}";
    }
}

3.3 @PathVariable

  • 作用:用于获取 URL 中的路径变量。
  • 示例
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @GetMapping("/users/{id}")
    public String getUser(@PathVariable Long id) {
        return "User with ID: " + id;
    }
}

3.4 @RequestParam

  • 作用:用于获取 HTTP 请求中的查询参数。
  • 示例
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SearchController {
    @GetMapping("/search")
    public String search(@RequestParam String keyword) {
        return "Searching for: " + keyword;
    }
}

3.5 @RequestBody

  • 作用:用于将 HTTP 请求的主体内容绑定到方法的参数上,通常用于处理 JSON 或 XML 格式的数据。
  • 示例
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @PostMapping("/users")
    public String createUser(@RequestBody User user) {
        // 处理用户创建逻辑
        return "User created: " + user.getName();
    }
}

class User {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

3.6 @RequestHeader

  • 作用:用于获取 HTTP 请求的头部信息。
  • 示例
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HeaderController {
    @GetMapping("/headers")
    public String getHeader(@RequestHeader("User-Agent") String userAgent) {
        return "User-Agent: " + userAgent;
    }
}

3.7 @CookieValue

  • 作用:用于获取 HTTP 请求中的 Cookie 值。
  • 示例
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CookieController {
    @GetMapping("/cookies")
    public String getCookie(@CookieValue("session_id") String sessionId) {
        return "Session ID: " + sessionId;
    }
}

3.8 @ModelAttribute

  • 作用:有两种使用方式。一是用于方法上,该方法会在控制器的每个处理方法执行前被调用,用于初始化一些数据;二是用于方法参数上,将请求参数绑定到一个对象上。
  • 示例
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ModelAttributeController {
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("message", "This is a pre - added message");
    }

    @GetMapping("/model")
    public String getModel(@ModelAttribute("message") String message) {
        return message;
    }
}

3.9 @SessionAttributes

  • 作用:用于将模型中的属性存储到会话中,以便在多个请求之间共享数据。
  • 示例
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SessionAttributes("user")
public class SessionAttributeController {
    @GetMapping("/addUser")
    public String addUserToSession(Model model) {
        model.addAttribute("user", "John Doe");
        return "User added to session";
    }

    @GetMapping("/getUser")
    public String getUserFromSession(@ModelAttribute("user") String user) {
        return "User from session: " + user;
    }
}

四、数据访问与事务管理注解

4.1 @Entity

  • 作用:用于标记一个 Java 类为 JPA 实体类,该类会映射到数据库中的一张表。
  • 示例
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    // Getters and Setters
}

4.2 @Table

  • 作用:用于指定实体类对应的数据库表名。
  • 示例
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "users")
public class User {
    // 实体类内容
}

4.3 @Id

  • 作用:用于标记实体类中的主键字段。
  • 示例:见 @Entity 示例。

4.4 @GeneratedValue

  • 作用:用于指定主键的生成策略,如自增、UUID 等。
  • 示例:见 @Entity 示例。

4.5 @Column

  • 作用:用于指定实体类的字段与数据库表列的映射关系,可设置列名、长度、是否可为空等属性。
  • 示例
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class User {
    @Id
    private Long id;
    @Column(name = "user_name", length = 50, nullable = false)
    private String name;

    // Getters and Setters
}

4.6 @Repository

  • 作用:在数据访问层使用,标记该类为数据访问组件,Spring 会自动处理数据访问异常。
  • 示例
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    // 自定义查询方法
}

4.7 @Transactional

  • 作用:用于声明事务边界,可以应用在类或方法上。在方法上使用时,该方法会在事务中执行;在类上使用时,该类的所有公共方法都会在事务中执行。可以设置事务的传播行为、隔离级别等属性。
  • 示例
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {
    private UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Transactional
    public void saveUser(User user) {
        userRepository.save(user);
    }
}

五、AOP 相关注解

5.1 @Aspect

  • 作用:用于标记一个类为切面类,该类中可以定义切点和通知。
  • 示例
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {
    @Pointcut("execution(* com.example.demo.service.*.*(..))")
    public void serviceMethods() {}

    @Before("serviceMethods()")
    public void beforeServiceMethod() {
        System.out.println("Before service method execution");
    }
}

5.2 @Pointcut

  • 作用:用于定义切点表达式,指定哪些方法会被切面拦截。
  • 示例:见 @Aspect 示例。

5.3 @Before

  • 作用:前置通知,在目标方法执行前执行。
  • 示例:见 @Aspect 示例。

5.4 @After

  • 作用:后置通知,在目标方法执行后执行,无论目标方法是否抛出异常。
  • 示例
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {
    @Pointcut("execution(* com.example.demo.service.*.*(..))")
    public void serviceMethods() {}

    @After("serviceMethods()")
    public void afterServiceMethod() {
        System.out.println("After service method execution");
    }
}

5.5 @AfterReturning

  • 作用:返回通知,在目标方法正常返回后执行,可以获取目标方法的返回值。
  • 示例
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {
    @Pointcut("execution(* com.example.demo.service.*.*(..))")
    public void serviceMethods() {}

    @AfterReturning(pointcut = "serviceMethods()", returning = "result")
    public void afterServiceMethodReturning(Object result) {
        System.out.println("Service method returned: " + result);
    }
}

5.6 @AfterThrowing

  • 作用:异常通知,在目标方法抛出异常时执行,可以获取异常信息。
  • 示例
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {
    @Pointcut("execution(* com.example.demo.service.*.*(..))")
    public void serviceMethods() {}

    @AfterThrowing(pointcut = "serviceMethods()", throwing = "ex")
    public void afterServiceMethodThrowing(Exception ex) {
        System.out.println("Service method threw exception: " + ex.getMessage());
    }
}

5.7 @Around

  • 作用:环绕通知,环绕目标方法执行,可以在目标方法执行前后进行增强处理,还可以控制目标方法是否执行。
  • 示例
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {
    @Pointcut("execution(* com.example.demo.service.*.*(..))")
    public void serviceMethods() {}

    @Around("serviceMethods()")
    public Object aroundServiceMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Before service method execution");
        Object result = joinPoint.proceed();
        System.out.println("After service method execution");
        return result;
    }
}

六、测试相关注解

6.1 @SpringBootTest

  • 作用:用于启动 Spring Boot 应用的上下文进行测试,可以模拟完整的应用环境。
  • 示例
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class MyServiceTest {
    @Autowired
    private MyService myService;

    @Test
    public void testMyService() {
        myService.doSomething();
    }
}

6.2 @MockBean

  • 作用:用于在测试中创建 Mock 对象,替换 Spring 容器中的实际 Bean,方便进行单元测试。
  • 示例
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;

import static org.mockito.Mockito.when;

@SpringBootTest
public class UserServiceTest {
    @Autowired
    private UserService userService;
    @MockBean
    private UserRepository userRepository;

    @Test
    public void testSaveUser() {
        User user = new User();
        when(userRepository.save(user)).thenReturn(user);
        userService.saveUser(user);
    }
}

6.3 @WebMvcTest

  • 作用:用于测试 Spring MVC 控制器,只加载与控制器相关的组件,不加载整个应用上下文,提高测试效率。
  • 示例
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(MyController.class)
public class MyControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testSayHello() throws Exception {
        mockMvc.perform(get("/hello"))
               .andExpect(status().isOk())
               .andExpect(content().string("Hello, World!"));
    }
}

6.4 @DataJpaTest

  • 作用:用于测试 JPA 数据访问层,自动配置嵌入式数据库,只加载与 JPA 相关的组件。
  • 示例
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

import static org.junit.jupiter.api.Assertions.assertNotNull;

@DataJpaTest
public class UserRepositoryTest {
    @Autowired
    private UserRepository userRepository;

    @Test
    public void testSaveUser() {
        User user = new User();
        user.setName("John Doe");
        User savedUser = userRepository.save(user);
        assertNotNull(savedUser.getId());
    }
}

七、其他注解

7.1 @Conditional

  • 作用:根据条件决定是否创建 Bean。可以自定义条件类,实现 Condition 接口。
  • 示例
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean
    @Conditional(MyCondition.class)
    public MyBean myBean() {
        return new MyBean();
    }
}

7.2 @ConditionalOnClass

  • 作用:当类路径中存在指定的类时,才会创建对应的 Bean。
  • 示例
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean
    @ConditionalOnClass(name = "com.example.SomeClass")
    public MyBean myBean() {
        return new MyBean();
    }
}

7.3 @ConditionalOnMissingBean

  • 作用:当容器中不存在指定类型的 Bean 时,才会创建对应的 Bean。
  • 示例
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionalOnMissingBean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean
    @ConditionalOnMissingBean(MyBean.class)
    public MyBean myBean() {
        return new MyBean();
    }
}

7.4 @ConditionalOnProperty

  • 作用:根据配置文件中的属性值决定是否创建 Bean。
  • 示例
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean
    @ConditionalOnProperty(name = "app.feature.enabled", havingValue = "true")
    public MyBean myBean() {
        return new MyBean();
    }
}

7.5 @Scheduled

  • 作用:用于创建定时任务,可指定任务的执行时间间隔、固定延迟等。
  • 示例
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MyScheduledTask {
    @Scheduled(fixedRate = 5000)
    public void doTask() {
        System.out.println("Task executed every 5 seconds");
    }
}

7.6 @EnableScheduling

  • 作用:启用 Spring 的定时任务功能,通常与 @Scheduled 配合使用。
  • 示例
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

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

7.7 @EnableAsync

  • 作用:启用 Spring 的异步方法调用功能,通常与 @Async 配合使用。
  • 示例
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

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

7.8 @Async

  • 作用:标记方法为异步方法,该方法会在单独的线程中执行。
  • 示例
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class MyAsyncService {
    @Async
    public void doAsyncTask() {
        // 异步执行的任务
    }
}

7.9 @ConfigurationProperties

  • 作用:用于将配置文件中的属性绑定到一个 Java 对象上。
  • 示例
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "app")
public class AppConfigProperties {
    private String name;
    private String version;

    // Getters and Setters
}

7.10 @EnableConfigurationProperties

  • 作用:启用 @ConfigurationProperties 注解的类,通常在配置类上使用。
  • 示例
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(AppConfigProperties.class)
public class AppConfig {
    // 配置类内容
}

以上涵盖了 Spring Boot 中大部分常用的注解,理解和掌握这些注解可以帮助开发者更高效地开发 Spring Boot 应用。