5000字指南,涵盖几乎所有SpringBoot注释及其详细说明

40 阅读21分钟

5000字指南,涵盖几乎所有SpringBoot注释及其详细说明

SpringBoot注释是提供有关Spring应用程序信息的元数据。

构建在Spring之上并包含其所有功能,

SpringBoot由于其生产就绪的环境而迅速成为开发人员的最爱,允许开发人员直接专注于逻辑,而无需配置和设置的麻烦。

SpringBoot是一个基于微服务的框架,允许在最短的时间内创建生产就绪的应用程序。

以下是SpringBoot的一些关键特性:

  • 它避免了Spring中繁重的XML配置。
  • 它提供了易于维护和创建REST端点的功能。
  • 它包括一个嵌入式Tomcat服务器。
  • 部署非常容易; WAR和WAR文件可以很容易地部署到Tomcat服务器上。

SpringBoot注释通常在包org.springframework.boot.autoconfigureorg.springframework.boot.autoconfigure.condition中找到,对于使用SpringBoot至关重要。

常见的SpringBoot注释、它们的用法和示例

1.@ SpringBoot应用程序:

此注释用于启动SpringBoot应用程序。

它结合了三个注释:@Configuration、@EnableAutoConfiguration和@ EnableScan。

范例:

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

2. @ restController:

这个注释表明这个类是一个RESTful控制器,结合了@Controller和@ResponseBody。

范例:

@RestController
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

在Spring 4中引入的这个annotation消除了使用@ResponseBody来注释控制器类中的每个请求处理方法的需要。

让我们看一个比较:

@Controller
@RequestMapping("/api/v1")
public class EmployeeController {
    @Autowired
    private EmployeeRepository employeeRepository;

    @GetMapping("/employees")
    public @ResponseBody List getAllEmployees() {
        return employeeRepository.findAll();
    }

    @GetMapping("/employees/{id}")
    public @ResponseBody ResponseEntity getEmployeeById(@PathVariable(value = "id") Long employeeId)
        throws ResourceNotFoundException {
        Employee employee = employeeRepository.findById(employeeId)
          .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
        return ResponseEntity.ok().body(employee);
    }

    @PostMapping("/employees")
    public @ResponseBody Employee createEmployee(@Valid @RequestBody Employee employee) {
        return employeeRepository.save(employee);
    }

    @PutMapping("/employees/{id}")
    public @ResponseBody ResponseEntity updateEmployee(@PathVariable(value = "id") Long employeeId,
         @Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException {
        Employee employee = employeeRepository.findById(employeeId)
        .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));

        employee.setEmailId(employeeDetails.getEmailId());
        employee.setLastName(employeeDetails.getLastName());
        employee.setFirstName(employeeDetails.getFirstName());
        final Employee updatedEmployee = employeeRepository.save(employee);
        return ResponseEntity.ok(updatedEmployee);
    }

    @DeleteMapping("/employees/{id}")
    public @ResponseBody Map deleteEmployee(@PathVariable(value = "id") Long employeeId)
         throws ResourceNotFoundException {
        Employee employee = employeeRepository.findById(employeeId)
       .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));

        employeeRepository.delete(employee);
        Map response = new HashMap<>();
        response.put("deleted", Boolean.TRUE);
        return response;
    }
}

在这个例子中,每个返回值都用@ResponseBody注释。

要在我们的示例中使用@RestController,我们需要将@Controller替换为@RestController,并从每个方法中删除@ResponseBody。生成的类应该如下所示:

@RestController
@RequestMapping("/api/v1")
public class EmployeeController {
    @Autowired
    private EmployeeRepository employeeRepository;

    @GetMapping("/employees")
    public List getAllEmployees() {
        return employeeRepository.findAll();
    }

    @GetMapping("/employees/{id}")
    public ResponseEntity getEmployeeById(@PathVariable(value = "id") Long employeeId)
        throws ResourceNotFoundException {
        Employee employee = employeeRepository.findById(employeeId)
          .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
        return ResponseEntity.ok().body(employee);
    }

    @PostMapping("/employees")
    public Employee createEmployee(@Valid @RequestBody Employee employee) {
        return employeeRepository.save(employee);
    }

    @PutMapping("/employees/{id}")
    public ResponseEntity updateEmployee(@PathVariable(value = "id") Long employeeId,
         @Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException {
        Employee employee = employeeRepository.findById(employeeId)
        .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));

        employee.setEmailId(employeeDetails.getEmailId());
        employee.setLastName(employeeDetails.getLastName());
        employee.setFirstName(employeeDetails.getFirstName());
        final Employee updatedEmployee = employeeRepository.save(employee);
        return ResponseEntity.ok(updatedEmployee);
    }

    @DeleteMapping("/employees/{id}")
    public Map deleteEmployee(@PathVariable(value = "id") Long employeeId)
         throws ResourceNotFoundException {
        Employee employee = employeeRepository.findById(employeeId)
       .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));

        employeeRepository.delete(employee);
        Map response = new HashMap<>();
        response.put("deleted", Boolean.TRUE);
        return response;
    }
}

有了这个注释,代码的可读性大大提高了。

3. @ RequestMapping:

此注释用于将Web请求映射到特定的处理程序方法。它可以应用于类或方法级别。

范例:

@RestController
@RequestMapping("/api")
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

4. @Autowired:

此注释用于Spring bean中的自动依赖注入。它可以应用于字段、构造函数或方法。

简单地说,它有两个功能:

  • @Autowired annotation用于自动注入bean。
  • @Autowired annotation用于构造函数注入、setter注入和字段注入。

范例:

@Service
public class MyService {
    private MyRepository repository;
​
    @Autowired
    public MyService(MyRepository repository) {
        this.repository = repository;
    }
}

再举一个例子:

@Autowired
private EmployeeRepository employeeRepository;

5. @Component:

@Component注释在Spring框架中用于将类标记为Spring管理的组件。

它允许Spring自动扫描并实例化它,使其通过依赖注入在应用程序中可用。

通常用于表示业务逻辑层、持久层、控制器等,它允许Spring管理它们的生命周期并注入依赖项。

简单地说,@Component注释用于将类标记为Spring管理的组件。

范例:

@Component
public class MyComponent {
    // ...
}

6. @Service:

此注释用于指示类是特殊类型的Springbean,通常用于业务逻辑。它通常被称为服务层。

范例:

@Service
public class MyService {
    // ...
}

更多SpringBoot注释及其详细说明。

7. @Repository:

这个注释用于指示一个类是一种特殊类型的Spring bean,通常用于数据库访问。

范例:

import org.springframework.stereotype.Repository;
​
@Repository
public class UserRepository {
​
    public void saveUser(User user) {
        // Implement logic to save user to database
    }
​
    public User getUserById(Long id) {
        // Implement logic to retrieve user by ID from database
        return null;
    }
​
    // Other data access methods...
}

在这个例子中,UserRepository class被标记为@Repository,表示它是Spring容器管理的数据访问组件,用于执行与用户数据相关的持久化操作。

这个注释可能对某些人不太熟悉,但是@Repository,像@Controller,@Service和@Component一样,表明对象应该由Spring管理。

@Repository用于持久层接口,它将其中一个实现类分配给Spring管理。

它与MyBatis的@Mapper非常相似。在一个程序中,MyBatis需要在编译时找到对应的映射器并生成一个代理类来实现数据库查询功能。

@Mapper和@Repository都用于持久层接口。

即使没有这个注释,我们也经常看不到错误,因为Spring的配置文件包含一个MapperScannerConfigurer bean,它扫描持久层接口并创建实现类供Spring管理。

类似地,在主应用程序类中添加@MapperScan可以达到与MapperScannerConfigurer相同的效果。

8. @Configuration:

这个注释用于将类声明为配置类。它通常与带@Bean注释的方法结合使用。

范例:

import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
​
import com.companyname.projectname.customer.CustomerService;
import com.companyname.projectname.order.OrderService;
​
@Configuration
public class Application {
​
    @Bean
    public CustomerService customerService() {
        return new CustomerService();
    }
​
    @Bean
    public OrderService orderService() {
        return new OrderService();
    }
}

上面的AppConfig类等价于下面的Spring XML:


    
    

这个注释通常用于配置诸如Swagger和MyBatis之类的属性。

9. @Value:

这个注释用于将属性文件或其他源中的值注入Springbean。

范例:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
​
@Component
public class MyComponent {
​
    @Value("${my.property}")
    private String myProperty;
​
    public void displayPropertyValue() {
        System.out.println("The value of my.property is: " + myProperty);
    }
}

在这个例子中,@Value("${my.property}")将Spring属性的值注入到myProperty字段中。

假设在应用程序的配置文件中有一个名为“my.property“的属性,

它的值将被注入到myProperty字段中。此注释通常用于代码生成器中,以避免硬编码值。

10. @ enableAutoConfiguration:

此注释启用了SpringBoot的自动配置机制,该机制基于类路径依赖项和属性配置应用程序。

范例:

@SpringBootApplication
@EnableAutoConfiguration
public class MyApplication {
    // ...
}

使用@EnableAutoConfiguration:

  • SpringBoot根据项目的依赖关系和配置自动配置各种应用程序组件,例如数据源,JPA和Web组件。
  • MyService类将由Spring容器自动扫描和管理。

没有@EnableAutoConfiguration:

  • 开发人员需要手动配置各种应用组件,增加了开发工作量。
  • MyService类不会被自动扫描,必须显式配置Spring容器管理。

要排除特定的自动配置类,可以使用@EnableAutoConfiguration的exclude属性:

范例:

@EnableAutoConfiguration(excludeName = {
    "org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration",
    "org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration"
})

11. @GetMapping、@PostMapping、@PutMapping、@DeleteMapping:

这些注释用于将特定的HTTP方法映射到处理程序方法。它们是相应HTTP方法的快捷方式。

范例:

@RestController
@RequestMapping("/api")
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
    
    @PostMapping("/data")
    public void saveData(@RequestBody Data data) {
        // Save data
    }
}

12. @PathVariable:

此注释用于将方法参数绑定到URL路径变量。

具有匹配方法参数名称和URL变量的示例:

@RestController
@RequestMapping("/api")
public class MyController {
    @GetMapping("/users/{id}")
    public User getUser(@PathVariable Long id) {
        // Retrieve user by given ID
    }
}

具有不同方法参数名称和URL变量的示例:

@RestController
@RequestMapping("/api")
public class MyController {
    @GetMapping("/users/{id}")
    public User getUser(@PathVariable("id") Long userId) {
        // Retrieve user by given ID
    }
}

13. @RequestParam:

此注释用于将方法参数绑定到请求参数。

范例:

@RestController
@RequestMapping("/api")
public class MyController {
    @GetMapping("/users")
    public List getUsers(@RequestParam("status") String status) {
        // Retrieve users by given status
    }
}

@RequestParam和@PathVariable的区别:

  • @RequestParam:
  • 用于从查询参数中获取值。
  • 查询参数通常通过URL在?符号之后传递(例如,?name=John&age=25)。
  • 用于方法参数中指定参数名称,Spring自动注入相应的值。
  • 适用于简单数据类型和使用application/x-www-form-urlencoded的GET或POST请求。

范例:

@GetMapping("/users")
public String getUserByName(@RequestParam("name") String name) {
    // Retrieve user by name
    return "User name: " + name;
}

总结:

  • @PathVariable:用于从URL路径获取值。
  • @RequestParam:用于从URL查询参数中获取值。

14. @RequestBody:

此注释用于将请求主体绑定到方法参数。它通常在RESTful API中用于接收JSON或XML有效载荷。

范例:

@RestController
@RequestMapping("/api")
public class MyController {
    @PostMapping("/users")
    public void createUser(@RequestBody User user) {
        // Create a new user
    }
}

在这个例子中,Spring会根据User自动将请求体转换为Content-Type对象。如果请求的Content-Typeapplication/json,请求体可能看起来像这样:

{
  "name": "xiaou",
  "age": 25
}

@RequestParam和@RequestBody的区别:

@RequestParam:

  • 用于查询参数,通常是简单的数据类型。
  • 适用于处理表单提交或带有查询参数的GET请求。

范例:

@GetMapping("/users")
public String getUserByName(@RequestParam("name") String name) {
    // Retrieve user by name
    return "User name: " + name;
}

@RequestBody:

  • 用于请求体,通常是复杂的数据类型(例如,JSON或XML)。
  • 适用于处理具有大型或复杂有效负载的POST请求。

范例:

@PostMapping("/users")
public String createUser(@RequestBody User user) {
    // Process received user object
    return "User created: " + user.toString();
}

总结:

  • @PathVariable:用于从URL路径获取参数。
  • @RequestParam:用于从URL查询字符串中获取参数。
  • @RequestBody:用于从HTTP请求体获取参数。

15. @Component:

这个注释用于指定当有多个相同类型的bean时应该注入哪个bean。

范例:


@Component("fooFormatter")
public class FooFormatter implements Formatter {
    public String format() {
        return "foo";
    }
}

@Component("barFormatter")
public class BarFormatter implements Formatter {
    public String format() {
        return "bar";
    }
}

@Component
public class FooService {
    @Autowired
    @Qualifier("fooFormatter")
    private Formatter formatter;
    
    // Additional code
}

在本例中,@Qualifier("fooFormatter")确保将fooFormatter bean注入到FooService中。

16. @ConditionalOnProperty:

此注释用于根据属性的值有条件地启用或禁用bean或配置。

范例:

@Configuration
@ConditionalOnProperty(name = "my.feature.enabled", havingValue = "true")
public class MyConfiguration {
    // Configuration that is enabled only if my.feature.enabled is true
}

17. @预定:

此注释用于以固定的时间间隔调度方法的执行。

范例:


@Component
public class MyScheduler {
    @Scheduled(fixedDelay = 5000)
    public void doSomething() {
        // Task executed at fixed intervals
    }
}

18. @Cacheable,@CachePut,@CacheEvict:

这些注释用于缓存方法结果。它们分别允许您缓存方法返回值、更新该高速缓存或从该高速缓存中逐出条目。

范例:

@Service
public class MyService {
    @Cacheable("users")
    public User getUserById(Long id) {
        // Retrieve user from database
    }
    
    @CachePut("users")
    public User updateUser(User user) {
        // Update user in database and cache
    }
    
    @CacheEvict("users")
    public void deleteUser(Long id) {
        // Delete user from database and cache
    }
}

Web注释

1.@ CookieValue:

用于从HTTP请求中提取特定的cookie值。

范例:


@GetMapping("/showUser")
public String showUser(@CookieValue("username") String username) {
    // Logic using the extracted cookie value
    return "User: " + username;
}

2. @ Modernity:

用于将请求参数绑定到模型对象,通常用于将表单数据传递给处理程序方法。

范例:

@PostMapping("/saveUser")
public String saveUser(@ModelAttribute User user) {
    // Logic to save user
    return "redirect:/users";
}

3. @ResponseStatus:

用于指定处理程序方法或异常的HTTP状态代码。

范例:

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
    // Custom exception
}

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleResourceNotFoundException() {
        return "resourceNotFound";
    }
}

4. @ExceptionHandler:

用于在控制器中定义方法以处理特定的异常。

范例:

@Controller
public class MyController {
    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(Exception ex) {
        ModelAndView modelAndView = new ModelAndView("error");
        modelAndView.addObject("errorMessage", ex.getMessage());
        return modelAndView;
    }
}

数据注释

1.@Entity:

用于将类标记为JPA实体,通常映射到数据库表。

范例:

@Entity
@Table(name = "employees")
public class Employee {
    // Entity attributes and methods
}

2. @Table:

用于指定实体映射到的表详细信息。

范例:

@Entity
@Table(name = "products", schema = "inventory")
public class Product {
    // Entity attributes and methods
}

3. @ID:

用于指定实体的主键。

范例:

@Entity
@Table(name = "employees")
public class Employee {
    @Id
    private Long id;
    // Other attributes and methods
}

4. @GeneratedValue:

用于指定主键的生成策略。

范例:

@Entity
@Table(name = "employees")
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    // Other attributes and methods
}

5. @Column:

用于指定字段映射到的列的详细信息。

范例:

@Entity
@Table(name = "employees")
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(name = "emp_name", length = 50, nullable = false)
    private String name;
    // Other attributes and methods
}

6. @Transient:

用于指定不应将字段持久化到数据库。

范例:

@Entity
@Table(name = "employees")
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(name = "emp_name", length = 50, nullable = false)
    private String name;
    
    @Transient
    private transientField;
    // Other attributes and methods
}

7. @PersistenceContext:

用于注入EntityManager以管理实体持久化操作。

@Service
public class EmployeeService {
    @PersistenceContext
    private EntityManager entityManager;
    // Other methods
}

8. @Query:

此注释用于声明自定义JPQL(Java持久性查询语言)查询。

它可以用于Repository接口或实体类中的方法。

范例:

@Repository
public interface EmployeeRepository extends JpaRepository {
    @Query("SELECT e FROM Employee e WHERE e.department = ?1")
    List findByDepartment(Department department);
}

9. @NamedQuery:

此注释用于在实体类上声明命名查询。

命名查询是可以在多个位置引用的预定义JPQL查询。

范例:

@Entity
@NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e")
public class Employee {
    // Entity attributes and methods
}

10. @Param:

此注释用于引用JPQL查询中的命名参数。

它在@Query注释中使用,并与查询字符串中的命名参数一起使用。

范例:


@Repository
public interface EmployeeRepository extends JpaRepository {
    @Query("SELECT e FROM Employee e WHERE e.department = :dept")
    List findByDepartment(@Param("dept") Department department);
}

11. @JoinTable:

此注释用于为实体之间的多对多关系指定连接表的详细信息。

范例:

@Entity
public class Student {
    @ManyToMany
    @JoinTable(name = "student_course",
               joinColumns = @JoinColumn(name = "student_id"),
               inverseJoinColumns = @JoinColumn(name = "course_id"))
    private List courses;
    // Other attributes and methods
}

12. @JoinColumn:

此注释用于指定实体关联的外键列,通常用于多对一或一对一关系。

范例:

@Entity
public class Employee {
    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;
    // Other attributes and methods
}

验证注释

这些注释通常用于Bean验证(JSR-380)规范的上下文中,用于验证JavaBean属性。

1.@Valid:

此注释用于指示嵌套对象的属性也应进行验证。它通常用于确保验证复杂对象的所有属性。

范例:

public class Address {
    @NotNull
    private String street;
    // Other attributes and methods
}

public class User {
    @Valid
    private Address address;
    // Other attributes and methods
}

2. @ Nothing:

此批注用于验证属性值是否为空。它通常应用于String、Collection、Map或基本数据类型。

范例:

public class User {
    @NotNull
    private String username;
    // Other attributes and methods
}

3. @Size:

该注释用于验证属性值的大小是否在指定的范围内。它可以应用于字符串、集合、映射或数组属性。

范例:


public class User {
    @Size(min = 2, max = 50)
    private String name;
    // Other attributes and methods
}

4. @Min:

此批注用于验证属性值是否大于或等于指定的最小值。它通常用于数字属性。

范例:


public class User {
    @Min(18)
    private int age;
    // Other attributes and methods
}

5. @Max:

此批注用于验证属性值是否小于或等于指定的最大值。它通常用于数字属性。

范例:

public class User {
    @Max(100)
    private int age;
    // Other attributes and methods
}

6. @Email:

此批注用于验证属性值是否符合电子邮件地址的格式。它通常应用于字符串属性。

范例:

public class User {
    @Email
    private String email;
    // Other attributes and methods
}

7. @Pattern:

此注释用于验证属性值是否与指定的正则表达式模式匹配。它允许自定义验证规则。

范例:


public class User {
    @Pattern(regexp = "^[A-Za-z0-9]+$")
    private String username;
    // Other attributes and methods
}

安全注解

这些注释通常用于Spring Security和OAuth2框架中,用于配置安全相关的功能和授权机制。

1.@EnableWebSecurity:

启用Spring Security的Web安全支持。

它通常放置在配置类上,以指示SpringBoot应用程序应该使用Spring Security。

范例:

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    // Configure security rules, etc.
}

2. @Configuration:

指示类是配置类。它通常与其他注释一起使用,以定义bean和配置应用程序的各种功能。

范例:

@Configuration
public class AppConfig {
    // Define beans, etc.
}

3. @EnableGlobalMethodSecurity:

启用全局方法级安全性。它可以配置PreAuthorizePostAuthorizeSecuredRolesAllowed注释。

范例:

@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
    // Configure method-level security rules
}

4. @PreAuthorize:

用于在执行方法之前执行授权检查。它允许使用Spring表达式语言(SpEL)来指定访问规则。

范例:

@PreAuthorize("hasRole('ROLE_ADMIN')")
public void deleteUser(User user) {
    // Logic for deleting a user
}

5. @PostAuthorize:

用于在执行方法后执行授权检查。它允许使用Spring表达式语言(SpEL)来指定访问规则。

范例:

@PostAuthorize("returnObject.owner == authentication.name")
public Object findDocument() {
    // Logic for returning a document
}

6. @Secured:

用于限制对方法的访问,指定调用该方法所需的角色。

范例:

@Secured("ROLE_ADMIN")
public void deleteUser(User user) {
    // Logic for deleting a user
}

7. @RolesAllowed:

用于限制对方法的访问,指定调用该方法所需的角色。

范例:

@RolesAllowed("ROLE_ADMIN")
public void deleteUser(User user) {
    // Logic for deleting a user
}

8. @EnableOAuth2Client、@EnableResourceServer、@EnableAuthorizationServer:

这些注释用于OAuth2配置,启用OAuth2客户端、资源服务器和授权服务器功能。它们通常放在配置类中。

范例:

@Configuration
@EnableOAuth2Client
public class OAuth2ClientConfig {
    // Configure OAuth2 client
}

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    // Configure resource server
}

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    // Configure authorization server
}

测试注释

这些注释通常在JUnit和Spring Framework中用于测试相关功能。

1. @RunWith:

用于指定JUnit 4中的测试运行器。在JUnit 5中,它已被@ExtendWith取代。

范例:

@RunWith(SpringRunner.class)
public class MySpringTest {
    // Test code
}

2. @SpringBootTest:

用于启动完整的Spring应用程序上下文以进行集成测试。它自动配置应用程序上下文。

范例:

@SpringBootTest
public class MyIntegrationTest {
    // Integration test code
}

3. @ WebMvcTest:

用于执行Spring MVC应用程序的单元测试。它只加载与Web相关的组件,如控制器和过滤器。

范例:

@WebMvcTest(UserController.class)
public class UserControllerTest {
    // Controller unit test code
}

4. @DataJpaTest:

用于执行JPA持久层的单元测试。它自动配置内存中的数据库(例如,H2)并扫描@Entity注释。

范例:

@DataJpaTest
public class UserRepositoryTest {
    // JPA unit test code
}

5. @ RestClientTest:

用于为Spring RestTemplate或WebClient客户端执行单元测试。它自动配置RestTemplate或WebClient bean。

范例:

@RestClientTest(MyRestClient.class)
public class MyRestClientTest {
    // Rest client unit test code
}

6. @ MockBean:

用于创建模拟对象并将其注入Spring上下文。它取代了Spring Bean进行单元测试。

范例:

@SpringBootTest
public class MyServiceTest {
    @MockBean
    private SomeDependency mockDependency;
    
    // Unit test code
}

7. @AutoConfigureMockMvc:

用于在Spring MVC测试中自动配置MockMvc。它用于模拟对控制器的请求。

范例:

@WebMvcTest(UserController.class)
@AutoConfigureMockMvc
public class UserControllerTest {
    @Autowired
    private MockMvc mockMvc;
    
    // Controller test code
}

8. @Test、@Before、@After、@BeforeEach、@AfterEach、@BeforeAll、@AfterAll:

用于JUnit测试方法的生命周期管理。@Test标记测试方法,而其他注释在测试方法之前或之后执行特定操作。

范例:

@Test
public void testSomething() {
    // Test method
}

@BeforeEach
public void setUp() {
    // Operations before each test method
}

@AfterEach
public void tearDown() {
    // Operations after each test method
}

9. @DisplayName:

用于指定测试类或测试方法的自定义名称。它用于生成更有意义的测试报告。

范例:

@Test
@DisplayName("Test User Registration Functionality")
public void testUserRegistration() {
    // Test method
}

10. @Disabled:

用于禁用测试类或测试方法。当在调试或开发过程中需要临时跳过某些测试时,使用它。

范例:

@Test
@Disabled("Temporarily disabled, waiting for fix")
public void testSomething() {
    // Test method
}

11. @ParameterizedTest,@ValueSource,@CsvSource:

用于参数化测试,允许使用不同的参数多次运行相同的测试方法。@ValueSource指定单个参数值的列表,而@CsvSource指定多个参数值。

范例:

@ParameterizedTest
@ValueSource(strings = {"apple", "banana", "orange"})
public void testFruit(String fruit) {
    // Test method with different fruit parameters
}

@ParameterizedTest
@CsvSource({"apple, 1", "banana, 2", "orange, 3"})
public void testFruit(String fruit, int count) {
    // Test method with different fruit and count parameters
}

12. @ExtendWith:

用于扩展测试运行时的功能,如参数解析和条件评估。

范例:

@ExtendWith(MyExtension.class)
public class MyTest {
    // Test methods
}

消息传递注释

这些注释通常用于Spring Framework for JMS(Java Message Service)消息传递功能,简化了JMS消息的生产和消费。

1.@ EnableJms:

启用JMS功能。通常放置在配置类上,以激活对JMS相关注释的支持。

范例:

@Configuration
@EnableJms
public class AppConfig {
    // Other configuration code
}

2. @ JmsListener:

将方法声明为JMS消息侦听器,用于接收JMS消息。它可以指定要监听的队列或主题。

范例:

@JmsListener(destination = "myQueue")
public void receiveMessage(String message) {
    // Process received message
}

3. @SendTo:

在消息处理方法中指定答复消息的目标。通常使用@JmsListener

范例:

@JmsListener(destination = "inputQueue")
@SendTo("outputQueue")
public String handleMessage(String message) {
    // Process message and return result
}

4. @ MessageMapping:

标识处理特定目标消息的方法。通常与Spring的WebSocket支持一起用于处理WebSocket消息。

范例:

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) {
    // Process message and return result
}

5. @Payload:

指定JMS消息处理方法中的有效负载参数,用于获取JMS消息内容。

范例:

@JmsListener(destination = "myQueue")
public void receiveMessage(@Payload String message) {
    // Process message
}

6. @Header:

指定JMS消息处理方法中的头参数,用于获取JMS消息头信息。

范例:

@JmsListener(destination = "myQueue")
public void receiveMessage(@Header("X-Custom-Header") String customHeader) {
    // Process message header
}

面向对象编程(AOP)注释

这些注释通常在Spring Framework中用于面向方面编程(AOP),以模块化横切关注点。

1.@Aspect:

定义一个方面,封装横切逻辑。方面是一个包含切入点和通知的类。

范例:

@Aspect
@Component
public class LoggingAspect {
    // Implementation of the aspect class
}

2. @Pointcut:

定义一个切入点,指定方面逻辑应用的位置。同一个切入点可以在多个通知中重用。

范例:

@Pointcut("execution(* com.example.service.*.*(..))")
private void serviceLayer() {}

3. @Before:

定义一个before通知,在方法执行之前执行。它在连接点之前运行。

范例:

@Before("serviceLayer()")
public void beforeAdvice() {
    // Logic for before advice
}

4. @After:

定义after建议,在方法执行后执行(无论方法结果如何)。它在连接点之后运行。

范例:

@After("serviceLayer()")
public void afterAdvice() {
    // Logic for after advice
}

5. @AfterReturning:

定义一个返回通知,在方法成功返回后执行。它仅在方法正常返回时运行。

范例:

@AfterReturning(pointcut = "serviceLayer()", returning = "result")
public void afterReturningAdvice(Object result) {
    // Logic for returning advice
}

6. @AfterThrowing:

定义一个抛出通知,在方法抛出异常后执行。它仅在方法引发异常时运行。

范例:

@AfterThrowing(pointcut = "serviceLayer()", throwing = "exception")
public void afterThrowingAdvice(Exception exception) {
    // Logic for throwing advice
}

7. @Around:

定义一个around通知,在方法执行之前和之后执行。它控制方法的执行。

范例:

@Around("serviceLayer()")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
    // Pre-execution logic
    Object result = joinPoint.proceed(); // Execute the advised method
    // Post-execution logic
    return result;
}

以下注释很少使用,因此简要概述。

致动器注释

这些注释用于启用和自定义SpringBootActuator,它为应用程序提供监视和管理功能。

这些注释用于启用和自定义SpringBootActuator,它为应用程序提供监视和管理功能。

@EnableActuator:

启用SpringBootActuator模块,提供应用程序监控和管理功能。

@Endpoint:

创建自定义终结点,允许您公开自定义监视和管理终结点。

范例:

@Endpoint(id = "customEndpoint")
public class CustomEndpoint {
    @ReadOperation
    public String read() {
        return "Custom Read Operation";
    }
}

@RestControllerEndpoint:

创建要用作REST控制器的REST样式终结点。

范例:

@RestControllerEndpoint(id = "customRestEndpoint")
public class CustomRestEndpoint {
    @GetMapping("/custom")
    public String custom() {
        return "Custom REST Endpoint";
    }
}

@ReadOperation:

指定在终结点中处理GET请求的方法。

@WriteOperation:

指定在终结点中处理POST请求的方法。

@DeleteOperation:

指定在终结点中处理HTTP请求的方法。

配置属性注释

这些注释用于将配置属性映射到JavaBean。

@ pagationProperties:

将属性从配置文件映射到Java Bean。

范例:

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

    // Getters and setters
}

@ConstructorBinding:

将配置属性绑定到构造函数参数,通常与@ConfigurationProperties一起使用。

@valid:

标记要验证的配置属性类,通常与JSR-380(Bean验证)一起使用。

国际化和本地化

  • @EnableMessageSource:启用消息源处理,通常用于国际化和本地化。
  • @EnableWebMvc:启用Spring MVC功能,通常用于配置类以支持Spring MVC。
  • @LocaleResolver:解析请求中的locale信息。
  • @MessageBundle:指定国际化消息资源文件的基名称。
  • @MessageSource:检索消息资源,通常与@Autowired一起使用。

记录和监控

@ Slf4j,@Log4j2,@ Log:

简化了为不同日志框架(SLF4J、Log4j2、JDK Logging)创建日志记录器的过程。

范例:

@Slf4j
public class MyService {
 public void doSomething() {
 log.info("Doing something");
 }
}

@Timed、@Counted、@ExceptionMetered:

添加度量以监视方法执行时间、调用计数和异常。

数据验证

@ Not,@NotBlank,@Email,@Size,@Pattern:

验证字段是否为非空、非空、电子邮件格式、大小范围和正则表达式模式匹配。

@ Positive、@ PositiveOrZero、@ Negative、@ NegativeOrZero:

验证数字是否为正数、非负数、负数或非正数。

GraphQL注释

  • @GraphQLApi:将类标记为GraphQL API类。
  • @GraphQLQuery、@GraphQLMutation、@GraphQLSubscription:定义GraphQL查询、变化和订阅。
  • @ GraphQLAgument、@GraphQLContext、@ GraphQLNonparameter、@GraphQLInputType、@GraphQLType:定义GraphQL参数、上下文、非空类型、输入类型和类型。

集成注释

  • @ IntegrationDataScan:扫描集成组件。
  • @MessagingGateway、@Transformer、@Splitter、@Aggregator、@ServiceActivator、@ InboundControllerAdapter、@ OutboundControllerAdapter、@Router、@BridgeTo:配置和定义集成组件。

Flyway数据库迁移

  • @FlywayTest:测试Flyway数据库迁移。
  • @FlywayTestExtension:扩展Flyway测试功能。
  • @FlywayTestExtension.Test,@FlywayTestExtension.BeforeMigration,@FlywayTestExtension.AfterMigration:标记测试方法并在迁移前后执行。

JUnit 5注释

  • @ExtendWith:扩展JUnit 5功能。
  • @TestInstance:配置测试实例的生命周期。
  • @TestTemplate:指定测试模板方法。
  • @DisplayNameGeneration:自定义生成测试显示名称的策略。
  • @Nested:创建嵌套的测试类。
  • @Tag:根据标签标记要运行的测试。
  • @DisabledOnOs, @EnabledOnOs, @DisabledIf, @EnabledIf:  Enables or disables tests based on conditions.

API文档注释

  • @Api,@ApiOperation,@ApiParam,@ApiModel,@ApiModelProperty:定义和描述API文档详细信息。

异常处理注释

  • @ControllerAdvice:定义全局异常处理程序。
  • @ ExceptionError:处理特定的异常。

GraphQL注释(附加)

  • @GraphQLSchema,@GraphQLQueryResolver,@GraphQLMutationResolver,@GraphQLSubscriptionResolver,@GraphQLResolver:定义GraphQL模式和解析器。

服务器发送事件(SSE)注释

  • @ SseEE:创建SSE事件发射器。
  • @SseEventSink:Incubate一个SSE事件接收器。

WebFlux注释

  • @RestController,@GetMapping,@PostMapping,@PutMapping,@DeleteMapping,@PatchMapping:定义WebFlux RESTful控制器和请求映射。

计量注释

  • @Timed:度量方法的执行时间。
  • @Counted:对方法调用进行计数。
  • @Gauge:将方法公开为Gauge度量。
  • @ExceptionMetered:度量方法异常率。

总结

这不是一个详尽的清单。SpringBoot提供了跨各种模块和功能的大量注释。

有关全面的列表和详细的用法,请参阅官方SpringBoot文档和特定于模块的指南。

本摘要涵盖了常用的注释,但几乎包括了您在典型项目中可能遇到的所有注释。