The 50 most commonly used annotations of SpringBoot (all dry goods, dry to death!)

The 50 most commonly used annotations of SpringBoot

​ SpringBoot provides many annotations that can help us quickly build applications. The following are the 50 most commonly used annotations of SpringBoot:

(1)@SpringBootApplication

Function: This is a combined annotation, including @Configuration, @EnableAutoConfiguration and @ComponentScan three annotations. The entry class used to identify the SpringBoot application.

@Configuration: Indicates that this class is a configuration class that defines one or more @Bean methods for creating and configuring beans in the Spring application context.

@EnableAutoConfiguration: Enables Spring Boot's auto-configuration mechanism, which automatically adds the required dependencies and configurations to enable the application to run.

@ComponentScan: Instructs Spring Boot to scan all @Component, @Service, @Repository, and @Controller annotated classes in the current package and its subpackages, and register them as Spring Beans.

The @SpringBootApplication annotation is usually used on the entry class of the Spring Boot application to start the Spring Boot application. It simplifies the configuration and startup process of Spring applications.

Example:

@SpringBootApplication
public class MyApplication {
    
    

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

(2)@RestController

Function: Similar to @Controller, but @RestController will automatically convert the return value to JSON format.

@RestController is an annotation introduced by Spring Framework 4.0, which is a combined annotation of @Controller and @ResponseBody. It is used to mark a class, indicating that this class is a RESTful style controller that can handle HTTP requests and return responses in JSON/XML format.

The @RestController annotation is used to replace the original @Controller annotation. By default, it converts the return value of the controller method into JSON format and returns it to the client as an HTTP response. If you need to return a response in XML format, you can use other annotations, such as @Produces and @Consumes.

Example:

@RestController
public class HelloController {
    
    

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

(3)@RequestMapping

Role: used to map request URLs and processing methods. @RequestMapping is a core annotation in the Spring MVC framework, which is used to map the relationship between HTTP requests and controller methods. It can be used at class level as well as method level to specify request URL and HTTP method (GET, POST, PUT, DELETE, etc.).

Example:

@RestController
@RequestMapping("/api")
public class UserController {
    
    

    @GetMapping("/users")
    public List<User> getUsers() {
    
    
        // 获取用户列表
    }

    @PostMapping("/users")
    public void createUser(@RequestBody User user) {
    
    
        // 创建新用户
    }

    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable Long id) {
    
    
        // 根据ID获取用户信息
    }

    @PutMapping("/users/{id}")
    public void updateUser(@PathVariable Long id, @RequestBody User user) {
    
    
        // 更新用户信息
    }

    @DeleteMapping("/users/{id}")
    public void deleteUser(@PathVariable Long id) {
    
    
        // 根据ID删除用户
    }
}

(4)@GetMapping

Role: used to map HTTP GET requests.

Example:

@RestController
@RequestMapping("/api")
public class UserController {
    
    

    @GetMapping("/users")
    public List<User> getUsers() {
    
    
        // 获取用户列表
    }

    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable Long id) {
    
    
        // 根据ID获取用户信息
    }
}

(5)@PostMapping

Role: used to map HTTP POST requests.

Example:

@RestController
@RequestMapping("/api")
public class UserController {
    
    

    @PostMapping("/users")
    public void createUser(@RequestBody User user) {
    
    
        // 创建新用户
    }
}

(6)@PutMapping

Role: used to map HTTP PUT requests.

Example:

@RestController
@RequestMapping("/api")
public class UserController {
    
    

    @PutMapping("/users/{id}")
    public void updateUser(@PathVariable Long id, @RequestBody User user) {
    
    
        // 更新用户信息
    }
}

(7)@DeleteMapping

Role: used to map HTTP DELETE requests.

Example:

@RestController
@RequestMapping("/api")
public class UserController {
    
    

    @DeleteMapping("/users/{id}")
    public void deleteUser(@PathVariable Long id) {
    
    
        // 根据ID删除用户
    }
}

(8)@RequestParam

Function: used to obtain the value of the request parameter.

Example:

@RestController
@RequestMapping("/api")
public class UserController {
    
    

    @GetMapping("/users")
    public List<User> getUsers(@RequestParam("page") int page, @RequestParam("size") int size) {
    
    
        // 分页获取用户列表
    }
}

(9)@PathVariable

Function: used to obtain the parameter value in the URL. @PathVariable is an annotation in the Spring MVC framework, which is used to bind variables in the HTTP request path to parameters of the controller method.

Example:

@RestController
@RequestMapping("/api")
public class UserController {
    
    

    @GetMapping("/users/{id}")
    public User getUser(@PathVariable Long id) {
    
    
        // 根据ID获取用户信息
    }
}

(10)@RequestBody

Role: used to convert the body of the HTTP request into the parameters of the method. @RequestBody is an annotation in the Spring MVC framework, which is used to bind the data in the HTTP request body to the parameters of the controller method.

Example:

@RestController
@RequestMapping("/api")
public class UserController {
    
    

    @PostMapping("/users")
    public User createUser(@RequestBody User user) {
    
    
        // 创建用户
    }
}

(11)@ResponseBody

Function: Used to convert the return value of the method into the body of the HTTP response. @ResponseBody is an annotation in the Spring MVC framework, which is used to convert the return value of the controller method into the data in the HTTP response body.

Example:

@RestController
@RequestMapping("/api")
public class UserController {
    
    

    @GetMapping("/users/{id}")
    public User getUser(@PathVariable Long id) {
    
    
        // 根据ID获取用户信息
    }
}

(12)@Autowired

Role: Used to automatically assemble beans in the Spring container.

Example:

@Service
public class UserServiceImpl implements UserService {
    
    

    @Autowired
    private UserRepository userRepository;

    // 实现UserService接口中的方法
}

(13)@Component

Role: Used to identify a class as a component in the Spring container. @Component is a general annotation in the Spring framework, which is used to mark a class as a Spring Bean.

Example:

@Component
public class UserServiceImpl implements UserService {
    
    

    // 实现UserService接口中的方法
}

(14)@Service

Role: Used to identify a class as a service component in the Spring container. @Service is an annotation in the Spring framework, which is used to mark a class as a service class (Service).

Example:

@Service
public class UserServiceImpl implements UserService {
    
    

    // 实现UserService接口中的方法
}

(15)@Repository

Role: Used to identify a class as a data access component in the Spring container. @Repository is an annotation in the Spring framework that is used to mark a class as a data access object (DAO).

Example:

@Repository
public class UserRepositoryImpl implements UserRepository {
    
    

    // 实现UserRepository接口中的方法
}

(16)@Configuration

Role: Used to identify a class as a Spring configuration class. @Configuration is an annotation in the Spring framework, which is used to mark a class as a configuration class.

Example:

@Configuration
public class AppConfig {
    
    

    @Bean
    public UserService userService() {
    
    
        return new UserServiceImpl();
    }

    @Bean
    public UserRepository userRepository() {
    
    
        return new UserRepositoryImpl();
    }
}

(17)@Value

Function: used to obtain the attribute value in the configuration file. @Value is an annotation in the Spring framework, which is used to inject the property value in the configuration file into the Bean object.

Example:

@Component
public class MyComponent {
    
    

    @Value("${my.property}")
    private String myProperty;

    // 其他方法
}
这个类使用@Component注解标注,表示这个类是一个Spring Bean,可以被其他的Spring Bean自动装配。

在属性级别上,@Value注解指定了需要注入的属性值,这个属性值可以通过${
    
    ...}的方式引用配置文件中的属性值。

在这个例子中,MyComponent类中的myProperty属性使用@Value注解指定了需要注入的属性值,Spring会自动将配置文件中名为my.property的属性值注入到这个属性中。

@Value注解用于注入配置文件中的属性值,使得开发者可以方便地从配置文件中获取属性值,并将其注入到Bean对象中。同时,使用@Value注解还可以方便地处理不同环境下的配置文件,如开发环境和生产环境的配置文件。

@Value注解是Spring框架中比较常用的注解之一,可以让开发者更加专注于业务逻辑的实现,而不必关心属性值的获取和注入细节。

(18)@Bean

Function: Used to register the object returned by a method into the Spring container. @Bean is an annotation in the Spring framework, which is used to register the object returned by a method as a Spring Bean.

Example:

@Configuration
public class AppConfig {
    
    

    @Bean
    public UserService userService() {
    
    
        return new UserServiceImpl();
    }

    @Bean
    public UserRepository userRepository() {
    
    
        return new UserRepositoryImpl();
    }
}

(19)@Import

Role: used to import other configuration classes or beans.

Example:

@Configuration
@Import({
    
    AppConfig1.class, AppConfig2.class})
public class AppConfig {
    
    

    // 其他方法
}

(20)@Conditional

Function: Used to determine whether to create a bean or execute configuration based on conditions.

Example:

@Configuration
public class AppConfig {
    
    

    @Bean
    @Conditional(DatabaseTypeCondition.class)
    public UserRepository userRepository() {
    
    
        return new UserRepositoryImpl();
    }

    // 其他方法
}

(21)@Profile

Role: The environment used to specify the configuration, such as a development environment, a test environment, or a production environment.

Example:

@Configuration
public class AppConfig {
    
    

    @Bean
    @Profile("dev")
    public UserService userServiceDev() {
    
    
        return new UserServiceDevImpl();
    }

    @Bean
    @Profile("prod")
    public UserService userServiceProd() {
    
    
        return new UserServiceProdImpl();
    }

    // 其他方法
}

(22)@PropertySource

Role: used to specify the location of the configuration file. @PropertySource is an annotation in the Spring framework that is used to specify the location of a set of property files so that these properties can be used in Spring applications.

Example:

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
    
    

    @Autowired
    private Environment environment;

    @Bean
    public UserService userService() {
    
    
        return new UserServiceImpl(environment.getProperty("userService.name"));
    }

    // 其他方法
}
这个类使用@Configuration注解标注,表示这个类是一个配置类,用于配置应用程序的Bean对象。

在类级别上,使用@PropertySource注解可以指定一个属性文件的位置。在这个例子中,使用@PropertySource注解指定了一个名为application.properties的属性文件,它位于classpath下。

在方法级别上,使用@Bean注解标注方法,表示这个方法返回一个Bean对象。在这个例子中,使用Environment对象从属性文件中读取属性值,并将这些属性值传递给UserService实例的构造方法。

@PropertySource注解用于指定一组属性文件的位置,使得开发者可以在Spring应用程序中使用这些属性。同时,使用Environment对象可以方便地读取属性文件中的属性值,并将这些属性值传递给Bean对象的构造方法或属性。

@PropertySource注解是Spring框架中比较常用的注解之一,可以让开发者更加灵活地管理和配置Spring Bean

(23)@Qualifier

Role: used to specify the name of the injected Bean.

Example:

@Component
public class UserServiceImpl implements UserService {
    
    

    @Autowired
    @Qualifier("userRepositoryImpl")
    private UserRepository userRepository;

    // 其他方法
}

(24)@ExceptionHandler

Role: used to handle exceptions.

Example:

@ControllerAdvice
public class GlobalExceptionHandler {
    
    

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

这个类使用@ControllerAdvice注解标注,表示这个类是一个全局异常处理器。在方法级别上,使用@ExceptionHandler注解可以指定一个方法来处理控制器中抛出的异常。

在这个例子中,使用@ExceptionHandler注解指定了一个名为handleException的方法,它处理所有类型的异常。当控制器中抛出异常时,会调用这个方法,并将异常对象作为参数传递给这个方法。

在这个方法中,使用ModelAndView对象来封装错误信息,并将视图名称设置为error。最后,返回这个ModelAndView对象,将错误信息显示到用户界面上。

@ExceptionHandler注解用于处理控制器中抛出的异常,使得开发者可以根据需要灵活地处理异常。同时,使用@ControllerAdvice注解可以将这个异常处理器应用于所有的控制器中。

@ExceptionHandler注解是Spring框架中比较常用的注解之一,可以让开发者更加灵活地处理控制器中的异常。

(25)@ResponseStatus

Role: used to specify the abnormal HTTP response status code.

Example:

@Controller
public class UserController {
    
    

    @GetMapping("/user/{id}")
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public UserDetails getUserDetails(@PathVariable("id") Long id) {
    
    
        // 查询用户信息
        UserDetails userDetails = userService.getUserDetails(id);
        if (userDetails == null) {
    
    
            throw new UserNotFoundException("User not found");
        }
        return userDetails;
    }

    @ExceptionHandler(UserNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public String handleUserNotFoundException(UserNotFoundException ex) {
    
    
        return ex.getMessage();
    }
}

(26)@ControllerAdvice

Role: used to handle exceptions globally.

@ControllerAdvice is an annotation in the Spring framework for defining global controller advice.

In the Spring MVC framework, controller notifications are special components that perform some additional logic processing before, after, or when an exception is thrown from a controller method. Global controller advice can be defined using the @ControllerAdvice annotation, which can be applied to all controllers.

Example:

@ControllerAdvice
public class GlobalControllerAdvice {
    
    

    @ModelAttribute("currentUser")
    public User getCurrentUser() {
    
    
        // 获取当前登录用户信息
        User currentUser = userService.getCurrentUser();
        return currentUser;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
    
    
        // 注册自定义的属性编辑器
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }

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

这个类使用@ControllerAdvice注解标注,表示这个类是一个全局控制器通知。在方法级别上,使用@ModelAttribute注解标注方法,表示这个方法会在所有控制器方法执行前执行,用于将当前登录用户信息添加到模型中。

使用@InitBinder注解标注方法,表示这个方法会在所有控制器方法执行前执行,用于注册自定义的属性编辑器。

使用@ExceptionHandler注解标注方法,表示这个方法会在控制器中抛出异常时执行,用于处理控制器方法中抛出的异常。

@ControllerAdvice注解用于定义全局控制器通知,使得开发者可以在所有控制器方法执行前、执行后或抛出异常时执行一些额外的逻辑处理。同时,使用@ModelAttribute注解可以将一些公共的模型数据添加到模型中,使用@InitBinder注解可以注册自定义的属性编辑器,使用@ExceptionHandler注解可以处理控制器方法中抛出的异常。

@ControllerAdvice注解是Spring框架中比较常用的注解之一,可以让开发者更加灵活地定义全局控制器通知。

(27)@CrossOrigin

Role: used to solve cross-domain problems.

@CrossOrigin is an annotation in the Spring framework to solve cross-origin resource sharing (CORS) problems.

Cross-origin resource sharing is part of browser security policy, which restricts browsers from sending and receiving HTTP requests between different domain names. Use the @CrossOrigin annotation to specify domain names and HTTP methods that allow cross-domain access.

Example:

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:8080", methods = {
    
    RequestMethod.GET, RequestMethod.POST})
public class ApiController {
    
    

    @GetMapping("/users")
    public List<User> getUsers() {
    
    
        // 查询用户信息
        List<User> users = userService.getUsers();
        return users;
    }
}

这个类使用@RestController注解标注,表示这个类是一个RESTful风格的控制器。在类级别上,使用@RequestMapping注解指定控制器处理的请求路径为/api。同时,使用@CrossOrigin注解可以指定允许跨域访问的域名和HTTP方法。

在这个例子中,使用@CrossOrigin注解指定允许来自http://localhost:8080域名的GET和POST请求访问该控制器中的方法。这意味着,在http://localhost:8080域名下的网页可以通过XMLHttpRequest对象发送GET和POST请求,访问该控制器中的方法。

@CrossOrigin注解用于解决跨域资源共享(CORS)问题,使得开发者可以更加灵活地控制允许跨域访问的域名和HTTP方法。它是一种简单但非常有效的解决方案,可以使得前端开发者更加轻松地开发跨域应用程序。

@CrossOrigin注解是Spring框架中比较常用的注解之一,可以让开发者更加灵活地解决跨域资源共享(CORS)问题。

(28)@Async

Role: Used to mark the method as asynchronous execution.

In the Spring framework, if a method needs to perform some time-consuming operations, if this method is executed in the main thread, the main thread will be blocked, and the user interface cannot respond to user operations. Using the @Async annotation can asynchronize the execution of this method, allowing the main thread to continue to perform other tasks and improve the responsiveness of the application.

Example:

@Service
public class UserService {
    
    

    @Async
    public CompletableFuture<UserDetails> getUserDetailsAsync(Long id) {
    
    
        // 查询用户信息
        UserDetails userDetails = userRepository.getUserDetails(id);
        return CompletableFuture.completedFuture(userDetails);
    }
}

这个类使用@Service注解标注,表示这个类是一个服务。在方法级别上,使用@Async注解标注方法,表示这个方法需要异步执行。

在这个例子中,getUserDetailsAsync方法使用@Async注解标注,表示这个方法需要异步执行。查询用户信息的操作在异步线程中执行,不会阻塞主线程。同时,这个方法返回一个CompletableFuture对象,表示异步执行的结果。

@Async注解用于异步执行方法,可以提高应用程序的响应性能。它是一种简单但非常有效的解决方案,可以使得开发者更加轻松地编写并发应用程序。

@Async注解是Spring框架中比较常用的注解之一,可以让开发者更加灵活地异步执行方法。需要注意的是,异步执行的方法必须在一个独立的线程中执行,因此需要使用线程池来管理异步线程的执行。

(29)@Cacheable

Role: used to cache the return value of the method.

In the Spring framework, if the return result of a method is fixed and the execution of this method is time-consuming, we can use the @Cacheable annotation to cache the return result of this method, and obtain it directly from the cache next time the method is executed As a result, repeated execution is avoided.

Example:

@Service
public class UserService {
    
    

    @Cacheable("userCache")
    public User getUser(Long id) {
    
    
        // 查询用户信息
        User user = userRepository.getUser(id);
        return user;
    }
}

这个类使用@Service注解标注,表示这个类是一个服务。在方法级别上,使用@Cacheable注解标注方法,表示这个方法返回的结果可以被缓存起来。

在这个例子中,getUser方法使用@Cacheable注解标注,表示这个方法的返回结果可以被缓存起来。查询用户信息的操作在第一次执行时会被执行,返回结果会被缓存到名为"userCache"的缓存中。下次执行getUser方法时,如果缓存中已经存在这个结果,就直接从缓存中获取结果,不需要再次执行查询操作。

@Cacheable注解用于缓存方法的返回结果,可以提高应用程序的执行效率。它是一种简单但非常有效的解决方案,可以使得开发者更加灵活地使用缓存来优化应用程序的性能。

@Cacheable注解是Spring框架中比较常用的注解之一,可以让开发者更加轻松地使用缓存来提高应用程序的性能。需要注意的是,使用缓存需要考虑缓存的生命周期和缓存的一致性,必要时需要使用缓存失效机制和缓存更新机制来维护缓存的一致性。

(30)@CacheEvict

Function: used to clear the cache.

@CacheEvict is an annotation in the Spring framework, which is used to clear the data in the cache.

In the Spring framework, if the execution of a method will invalidate the cached data, we can use the @CacheEvict annotation to clear the cached data of this method, so that the next time the method is executed, the data will be re-queried and cached.

Example:

@Service
public class UserService {
    
    

    @Cacheable("userCache")
    public User getUser(Long id) {
    
    
        // 查询用户信息
        User user = userRepository.getUser(id);
        return user;
    }
    
    @CacheEvict("userCache")
    public void clearCache() {
    
    
        // 清空缓存
    }
}

这个类使用@Service注解标注,表示这个类是一个服务。在方法级别上,使用@Cacheable注解标注getUser方法,表示这个方法的返回结果可以被缓存起来。同时,使用@CacheEvict注解标注clearCache方法,表示这个方法会清空名为"userCache"的缓存。

在这个例子中,getUser方法使用@Cacheable注解标注,表示这个方法的返回结果可以被缓存起来。查询用户信息的操作在第一次执行时会被执行,返回结果会被缓存到名为"userCache"的缓存中。下次执行getUser方法时,如果缓存中已经存在这个结果,就直接从缓存中获取结果,不需要再次执行查询操作。

当调用clearCache方法时,@CacheEvict注解会清空名为"userCache"的缓存,下次执行getUser方法时,就需要重新查询数据并缓存起来。

@CacheEvict注解用于清空缓存中的数据,可以使得开发者更加灵活地控制缓存的生命周期和缓存的一致性。它是一种简单但非常有效的解决方案,可以使得开发者更加轻松地使用缓存来提高应用程序的性能。

@CacheEvict注解是Spring框架中比较常用的注解之一,可以让开发者更加灵活地控制缓存的生命周期和缓存的一致性。需要注意的是,清空缓存需要谨慎操作,必要时需要考虑缓存的失效机制和缓存更新机制来维护缓存的一致性。

(31)@CachePut

Function: used to update the data in the cache.

@CachePut is an annotation in the Spring framework for updating or adding data in the cache.

In the Spring framework, if the execution of a method will cause the update or addition of cached data, we can use the @CachePut annotation to update or add the return result of this method to the cache.

Example:

@Service
public class UserService {
    
    

    @Cacheable("userCache")
    public User getUser(Long id) {
    
    
        // 查询用户信息
        User user = userRepository.getUser(id);
        return user;
    }
    
    @CachePut("userCache")
    public User updateUser(Long id, User user) {
    
    
        // 更新用户信息
        User updatedUser = userRepository.updateUser(id, user);
        return updatedUser;
    }
}

这个类使用@Service注解标注,表示这个类是一个服务。在方法级别上,使用@Cacheable注解标注getUser方法,表示这个方法的返回结果可以被缓存起来。同时,使用@CachePut注解标注updateUser方法,表示这个方法会更新或添加名为"userCache"的缓存。

在这个例子中,getUser方法使用@Cacheable注解标注,表示这个方法的返回结果可以被缓存起来。查询用户信息的操作在第一次执行时会被执行,返回结果会被缓存到名为"userCache"的缓存中。下次执行getUser方法时,如果缓存中已经存在这个结果,就直接从缓存中获取结果,不需要再次执行查询操作。

当调用updateUser方法时,@CachePut注解会更新或添加名为"userCache"的缓存,下次执行getUser方法时,就可以从缓存中获取更新后的用户信息。

@CachePut注解用于更新或添加缓存中的数据,可以使得开发者更加灵活地控制缓存的生命周期和缓存的一致性。它是一种简单但非常有效的解决方案,可以使得开发者更加轻松地使用缓存来提高应用程序的性能。

@CachePut注解是Spring框架中比较常用的注解之一,可以让开发者更加灵活地控制缓存的生命周期和缓存的一致性。需要注意的是,更新或添加缓存需要谨慎操作,必要时需要考虑缓存的失效机制和缓存更新机制来维护缓存的一致性。

(32)@Transactional

Role: used to specify the scope of the transaction.

Example:


(33)@EnableTransactionManagement

Function: used to enable the transaction management function.

@Transactional is an annotation in the Spring framework that is used to identify a method or class that needs to be operated using transactions.

In the Spring framework, if a method needs to operate on the database, we can use the @Transactional annotation to ensure that the operation is performed in a transaction, thereby ensuring the atomicity, consistency, isolation and persistence of the operation.

Example:

@Service
@Transactional
public class UserService {
    
    

    @Autowired
    private UserRepository userRepository;

    public void createUser(User user) {
    
    
        userRepository.save(user);
    }
    
    public void updateUser(Long id, User user) {
    
    
        User existingUser = userRepository.findById(id);
        
        if (existingUser != null) {
    
    
            existingUser.setName(user.getName());
            existingUser.setEmail(user.getEmail());
            userRepository.save(existingUser);
        }
    }
}

这个类使用@Service注解标注,表示这个类是一个服务。同时,在类级别上使用@Transactional注解标注,表示这个类中的所有方法都需要使用事务进行操作。

在这个例子中,createUser和updateUser方法都需要对数据库进行操作,因此使用userRepository来保存或更新用户信息。由于这个类使用了@Transactional注解来标识,因此userRepository的操作都在一个事务中进行,从而保证操作的原子性、一致性、隔离性和持久性。

@Transactional注解用于标识一个方法或类需要使用事务进行操作,可以使得开发者更加灵活地控制事务的使用。它是一种简单但非常有效的解决方案,可以使得开发者更加轻松地使用事务来提高应用程序的性能和数据一致性。

@Transactional注解是Spring框架中比较常用的注解之一,可以让开发者更加灵活地控制事务的使用。需要注意的是,事务的使用需要谨慎操作,必要时需要考虑事务的隔离级别、超时时间和回滚机制等来维护数据的一致性和应用程序的性能。

(34)@EnableAspectJAutoProxy

Role: used to enable the AOP function.

@EnableAspectJAutoProxy is an annotation in the Spring framework to enable automatic proxying for programming using AOP (aspect-oriented programming).

In the Spring framework, if we need to use AOP to implement certain functions, we can use the @EnableAspectJAutoProxy annotation to enable the automatic proxy function, so that proxy objects are automatically generated for us at runtime for aspect programming.

Example:

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
    
    

    @Bean
    public MyAspect myAspect() {
    
    
        return new MyAspect();
    }
    
    @Bean
    public UserService userService() {
    
    
        return new UserService();
    }
}

这个类使用@Configuration注解标注,表示这个类是一个配置类。同时,在类级别上使用@EnableAspectJAutoProxy注解标注,表示这个配置类需要启用自动代理功能。

在这个例子中,我们定义了一个MyAspect类来实现某些功能的切面编程。为了让Spring框架能够自动为我们生成代理对象,我们需要将MyAspect类加入到Spring容器中,并且使用@Bean注解标注。另外,我们还定义了一个UserService类来实现某些业务功能。

@EnableAspectJAutoProxy注解用于启用自动代理功能,可以使得开发者更加方便地使用AOP来实现某些功能。它是一种简单但非常有效的解决方案,可以让开发者更加轻松地使用切面编程来提高应用程序的性能和可维护性。

@EnableAspectJAutoProxy注解是Spring框架中比较常用的注解之一,可以让开发者更加方便地使用AOP来实现某些功能。需要注意的是,AOP的使用需要谨慎操作,必要时需要考虑AOP的切面逻辑、切入点和通知类型等来维护应用程序的性能和可维护性。

(35)@Aspect

Function: used to define the cut surface.

@Aspect is an annotation in the Spring framework, which is used to identify a class as an aspect class, so that aspect logic can be defined in the class to implement AOP (aspect-oriented programming).

In the Spring framework, if we need to use AOP to achieve certain functions, we can use the @Aspect annotation to identify a class as an aspect class. In the aspect class, we can define the aspect logic, including entry point, notification type, and aspect order, so as to realize the function of AOP programming.

Example:

@Aspect
@Component
public class MyAspect {
    
    

    @Before("execution(* com.example.UserService.*(..))")
    public void beforeAdvice() {
    
    
        System.out.println("Before advice is executed.");
    }
    
    @After("execution(* com.example.UserService.*(..))")
    public void afterAdvice() {
    
    
        System.out.println("After advice is executed.");
    }
}

这个类使用@Aspect注解标识,表示这个类是一个切面类。同时,我们还使用@Component注解标识这个类,以便Spring框架能够自动将它加入到Spring容器中。

在这个例子中,我们定义了一个MyAspect类来实现某些功能的切面编程。在这个类中,我们定义了两个通知类型,即@Before@After,分别表示在目标方法执行前和执行后执行某些操作。这些通知类型的执行条件是通过切入点表达式来定义的。

@Aspect注解用于标识一个类为切面类,可以使得开发者更加方便地使用AOP来实现某些功能。它是一种简单但非常有效的解决方案,可以让开发者更加轻松地使用切面编程来提高应用程序的性能和可维护性。

@Aspect注解是Spring框架中比较常用的注解之一,用于标识一个类为切面类。需要注意的是,AOP的使用需要谨慎操作,必要时需要考虑切入点、通知类型和切面顺序等来维护应用程序的性能和可维护性。

(36)@Pointcut

Function: used to define the cut point.

@Pointcut is an annotation in the Spring framework, which is used to define a pointcut, so that the advice type can be defined on the pointcut to implement AOP (aspect-oriented programming).

In the Spring framework, if we need to use AOP to achieve certain functions, we can use the @Pointcut annotation to define a pointcut. At the entry point, we can define aspect logic, including notification type and aspect sequence, etc., so as to realize the function of AOP programming.

Example:

@Aspect
@Component
public class MyAspect {
    
    

    @Pointcut("execution(* com.example.UserService.*(..))")
    public void userServicePointcut() {
    
    }
    
    @Before("userServicePointcut()")
    public void beforeAdvice() {
    
    
        System.out.println("Before advice is executed.");
    }
    
    @After("userServicePointcut()")
    public void afterAdvice() {
    
    
        System.out.println("After advice is executed.");
    }
}

这个类使用@Aspect注解标识,表示这个类是一个切面类。同时,我们还使用@Component注解标识这个类,以便Spring框架能够自动将它加入到Spring容器中。

在这个例子中,我们定义了一个MyAspect类来实现某些功能的切面编程。在这个类中,我们使用@Pointcut注解定义了一个切入点,即userServicePointcut()方法。在这个切入点上,我们定义了两个通知类型,即@Before@After,分别表示在目标方法执行前和执行后执行某些操作。

@Pointcut注解用于定义一个切入点,可以使得开发者更加方便地使用AOP来实现某些功能。它是一种简单但非常有效的解决方案,可以让开发者更加轻松地使用切面编程来提高应用程序的性能和可维护性。

@Pointcut注解是Spring框架中比较常用的注解之一,用于定义一个切入点。需要注意的是,AOP的使用需要谨慎操作,必要时需要考虑切入点、通知类型和切面顺序等来维护应用程序的性能和可维护性。

(37)@Before

Function: Used to perform notification before method execution.

@Before is an annotation in the Spring framework, which is used to define the type of advice executed before the execution of the target method to achieve AOP (aspect-oriented programming).

In the Spring framework, if we need to perform some operations before the execution of the target method, we can use the @Before annotation to define a notification type. In this notification type, we can write our own logic code to realize the function of AOP programming.

Example:

@Aspect
@Component
public class MyAspect {
    
    

    @Before("execution(* com.example.UserService.*(..))")
    public void beforeAdvice() {
    
    
        System.out.println("Before advice is executed.");
    }
}

(38)@After

Function: Used to perform notification after method execution.

@After is an annotation in the Spring framework, which is used to define the type of advice that is executed after the execution of the target method to achieve AOP (aspect-oriented programming).

In the Spring framework, if we need to perform some operations after the execution of the target method, we can use the @After annotation to define a notification type. In this notification type, we can write our own logic code to realize the function of AOP programming.

Example:

@Aspect
@Component
public class MyAspect {
    
    

    @After("execution(* com.example.UserService.*(..))")
    public void afterAdvice() {
    
    
        System.out.println("After advice is executed.");
    }
}

(39)@Around

Role: Used to perform notifications before and after method execution.

@Around is an annotation in the Spring framework, which is used to define the type of advice executed before and after the execution of the target method to achieve AOP (aspect-oriented programming).

In the Spring framework, if we need to perform certain operations before and after the execution of the target method, we can use the @Around annotation to define a notification type. In this notification type, we can write our own logic code to realize the function of AOP programming.

Example:

@Aspect
@Component
public class MyAspect {
    
    

    @Around("execution(* com.example.UserService.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
    
    
        System.out.println("Before advice is executed.");
        Object result = joinPoint.proceed();
        System.out.println("After advice is executed.");
        return result;
    }
}

(40)@AfterReturning

Function: Used to perform notification after the method returns the result.

@AfterReturning is an annotation in the Spring framework, which is used to define the type of advice that is executed after the target method returns the result to achieve AOP (aspect-oriented programming).

In the Spring framework, if we need to perform some operations after the target method returns the result, we can use the @AfterReturning annotation to define a notification type. In this notification type, we can write our own logic code to realize the function of AOP programming.

Example:

@Aspect
@Component
public class MyAspect {
    
    

    @AfterReturning(pointcut = "execution(* com.example.UserService.*(..))", returning = "result")
    public void afterReturningAdvice(Object result) {
    
    
        System.out.println("After returning advice is executed. Result is " + result);
    }
}

(41)@AfterThrowing

Function: Used to perform notification after the method throws an exception.

@AfterThrowing is an annotation in the Spring framework, which is used to define the type of advice that is executed after the target method throws an exception to achieve AOP (aspect-oriented programming).

In the Spring framework, if we need to perform some operations after the target method throws an exception, we can use the @AfterThrowing annotation to define a notification type. In this notification type, we can write our own logic code to realize the function of AOP programming.

Example:

@Aspect
@Component
public class MyAspect {
    
    

    @AfterThrowing(pointcut = "execution(* com.example.UserService.*(..))", throwing = "ex")
    public void afterThrowingAdvice(Exception ex) {
    
    
        System.out.println("After throwing advice is executed. Exception is " + ex);
    }
}

(42)@Order

Role: Used to specify the execution order of the aspects.

@Order is an annotation in the Spring framework, which is used to define the execution order of aspects.

In the Spring framework, if there are multiple aspect classes that need to perform aspect processing on the same method, the execution order of these aspect classes may affect the final result. In order to control the execution order of these aspect classes, we can use the @Order annotation to define their execution order.

The @Order annotation can be applied to aspect classes to specify the order in which aspects are executed. Its parameter is an integer, and the smaller the value, the higher the priority. If the value is the same, it will be sorted according to the natural order of the class name.

Example:

@Aspect
@Component
@Order(1)
public class MyAspect1 {
    
    

    @Before("execution(* com.example.UserService.*(..))")
    public void beforeAdvice() {
    
    
        System.out.println("Before advice from MyAspect1 is executed.");
    }
}

@Aspect
@Component
@Order(2)
public class MyAspect2 {
    
    

    @Before("execution(* com.example.UserService.*(..))")
    public void beforeAdvice() {
    
    
        System.out.println("Before advice from MyAspect2 is executed.");
    }
}

(43)@Slf4j

Role: Used to simplify logging.

@Slf4j is an annotation in the Lombok framework to automatically generate loggers in Java classes.

In Java development, logging is a very important part, which can help us better understand the operation of the program, so as to better debug and optimize. Usually, we need to manually introduce logging frameworks (such as Log4j, SLF4J, etc.) and write corresponding logging code. These codes can be cumbersome and error-prone. To simplify this process, the Lombok framework provides a @Slf4j annotation that automatically generates loggers in Java classes.

Using the @Slf4j annotation is very simple, just add this annotation to the Java class. When in use, we can directly use the log variable to record the log without introducing other log frameworks

Example:

@Slf4j
public class MyService {
    
    

    public void doSomething() {
    
    
        log.debug("This is a debug message.");
        log.info("This is an info message.");
        log.error("This is an error message.");
    }
}

在这个例子中,我们定义了一个MyService类,并使用@Slf4j注解来自动生成日志记录器。然后,在doSomething()方法中,我们直接使用log变量来记录日志,而不需要再引入其他的日志框架。

需要注意的是,使用@Slf4j注解需要在编译器中安装Lombok插件,否则可能会出现编译错误。另外,虽然@Slf4j注解非常方便,但在实际应用中,我们还需要根据实际情况选择合适的日志框架,并编写相应的日志记录代码。

总之,@Slf4jLombok框架中的一个注解,可以在Java类中自动生成日志记录器,从而简化日志记录的过程。它是一种极为方便的解决方案,可以提高应用程序的可维护性和可读性。

(44)@Data

Function: Used to automatically generate getters, setters, toString, hashCode and equals methods of JavaBean.

@Data is an annotation in the Lombok framework, which can automatically generate getter, setter, equals, hashCode and toString methods of Java classes.

In Java development, we often need to write some POJO classes to represent data structures. These classes usually contain some member variables, and need to write corresponding methods such as getter, setter, equals, hashCode and toString. These methods are often similar and more cumbersome. To simplify this process, the Lombok framework provides a @Data annotation that automatically generates these methods.

Using the @Data annotation is very simple, just add this annotation to the Java class. When in use, we can directly access the member variables of the class, and can automatically generate corresponding methods such as getter, setter, equals, hashCode and toString.

Example:

@Data
public class User {
    
    
    private Long id;
    private String name;
    private Integer age;
}

(45)@NoArgsConstructor

Function: Used to generate a parameterless constructor.

@NoArgsConstructor is an annotation in the Lombok framework, which is used to automatically generate a parameterless constructor.

In Java development, we often need to write some POJO classes to represent data structures. These classes usually contain some member variables, and need to write the corresponding construction method. In some cases, we may need to write a no-argument constructor to create an instance of an object. This constructor is usually simple and takes no parameters. In order to simplify this process, the Lombok framework provides a @NoArgsConstructor annotation, which can automatically generate a no-argument constructor.

Using the @NoArgsConstructor annotation is very simple, just add this annotation to the Java class. When in use, we can directly create an instance of an object without manually writing a parameterless construction method.

Example:

@NoArgsConstructor
public class User {
    
    
    private Long id;
    private String name;
    private Integer age;
}

在这个例子中,我们定义了一个User类,并使用@NoArgsConstructor注解来自动生成一个无参构造方法。然后,在其他的Java类中,我们可以直接创建User对象的实例,而不需要手动编写无参构造方法。

需要注意的是,使用@NoArgsConstructor注解需要在编译器中安装Lombok插件,否则可能会出现编译错误。另外,虽然@NoArgsConstructor注解非常方便,但在实际应用中,我们还需要根据实际情况选择合适的构造方法,并编写相应的代码。

总之,@NoArgsConstructorLombok框架中的一个注解,用于自动生成一个无参构造方法,从而简化Java开发的过程。它是一种极为方便的解决方案,可以提高应用程序的可维护性和可读性。

(46)@AllArgsConstructor

Function: Used to generate a full-parameter constructor.

@AllArgsConstructor is an annotation in the Lombok framework, which is used to automatically generate a full parameter constructor.

In Java development, we often need to write some POJO classes to represent data structures. These classes usually contain some member variables, and need to write the corresponding construction method. In some cases, we may need to write a full parameter constructor to initialize all member variables. This constructor usually contains all member variables as parameters. In order to simplify this process, the Lombok framework provides a @AllArgsConstructor annotation, which can automatically generate a full parameter constructor.

Using the @AllArgsConstructor annotation is very simple, just add this annotation to the Java class. When in use, we can directly create an instance of the object and pass in the corresponding parameters without manually writing a full-parameter construction method.

Example:

@AllArgsConstructor
public class User {
    
    
    private Long id;
    private String name;
    private Integer age;
}

在这个例子中,我们定义了一个User类,并使用@AllArgsConstructor注解来自动生成一个全参构造方法。然后,在其他的Java类中,我们可以直接创建User对象的实例,并传入相应的参数,而不需要手动编写全参构造方法。

需要注意的是,使用@AllArgsConstructor注解需要在编译器中安装Lombok插件,否则可能会出现编译错误。另外,虽然@AllArgsConstructor注解非常方便,但在实际应用中,我们还需要根据实际情况选择合适的构造方法,并编写相应的代码。

总之,@AllArgsConstructorLombok框架中的一个注解,用于自动生成一个全参构造方法,从而简化Java开发的过程。它是一种极为方便的解决方案,可以提高应用程序的可维护性和可读性。

(47)@Builder

Function: used to generate the constructor of the Builder pattern.

@Builder is an annotation in the Lombok framework, which is used to automatically generate a constructor of the Builder pattern.

In Java development, we often need to write some POJO classes to represent data structures. These classes usually contain some member variables, and need to write the corresponding construction method. In some cases, we may need to write a Builder pattern constructor for convenient creation of object instances. Builder mode is a design mode for creating objects, which can set the properties of objects through chain calls, and finally create an immutable object. In order to simplify this process, the Lombok framework provides a @Builder annotation, which can automatically generate a constructor of the Builder pattern.

Using the @Builder annotation is very simple, just add this annotation to the Java class. When in use, we can use chain calls to set the properties of the object, and finally create an immutable object.

Example:

@Builder
public class User {
    
    
    private Long id;
    private String name;
    private Integer age;
}
在这个例子中,我们定义了一个User类,并使用@Builder注解来自动生成一个Builder模式的构造器。然后,在其他的Java类中,我们可以使用链式调用的方式设置User对象的属性,并最终创建一个不可变的对象。

需要注意的是,使用@Builder注解需要在编译器中安装Lombok插件,否则可能会出现编译错误。另外,虽然@Builder注解非常方便,但在实际应用中,我们还需要根据实际情况选择合适的构造方法,并编写相应的代码。

总之,@BuilderLombok框架中的一个注解,用于自动生成一个Builder模式的构造器,从而简化Java开发的过程。它是一种极为方便的解决方案,可以提高应用程序的可维护性和可读性。

(48)@EqualsAndHashCode

Function: used to generate hashCode and equals methods.

@EqualsAndHashCode is an annotation in the Lombok framework for automatically generating equals() and hashCode() methods.

In Java development, we often need to compare whether two objects are equal, and need to generate a hashCode value based on the properties of the object. In order to simplify this process, the Lombok framework provides a @EqualsAndHashCode annotation that can automatically generate equals() and hashCode() methods.

Using the @EqualsAndHashCode annotation is very simple, just add this annotation to the Java class. When in use, Lombok will automatically generate equals() and hashCode() methods based on the attributes of the class. If all properties of two objects are equal, then their equals() method returns true and their hashCode() method returns the same value.

Example:

@EqualsAndHashCode
public class User {
    
    
    private Long id;
    private String name;
    private Integer age;
}

(49)@ToString

Function: used to generate the toString method.

@ToString is an annotation in the Lombok framework, which is used to automatically generate the toString() method.

In Java development, we often need to convert objects to strings for easy output or logging. In order to simplify this process, the Lombok framework provides a @ToString annotation, which can automatically generate the toString() method.

Using the @ToString annotation is very simple, just add this annotation to the Java class. When in use, Lombok will automatically generate the toString() method based on the attributes of the class. This method will output the name of the class and the names and values ​​​​of all attributes. If you need to exclude certain attributes, you can use the exclude attribute to specify the excluded attributes.

Example:

@ToString(exclude = "password")
public class User {
    
    
    private Long id;
    private String name;
    private String password;
}

(50)@Getter

Role: Used to generate getters methods.

@Getter is an annotation in the Lombok framework for automatically generating getter methods.

In Java development, we often need to write getter and setter methods for properties of classes. In order to simplify this process, the Lombok framework provides a @Getter annotation that can automatically generate getter methods.

Using the @Getter annotation is very simple, just add this annotation to the Java class. When in use, Lombok will automatically generate the corresponding getter method according to the properties of the class. If you need to generate a setter method, you can use the @Setter annotation.

Example:

@Getter
public class User {
    
    
    private Long id;
    private String name;
    private Integer age;
}

Welcome to add!

Guess you like

Origin blog.csdn.net/qq_46138492/article/details/129476788