Common annotations for Spring, SpringMVC, SpringBoot, and SpringCloud frameworks

Spring Common Annotations

Configuration configuration class related notes

  • @Configuration : Annotated on the class, declaring the class as a Spring configuration class

    When Spring starts, it will automatically scan and load all configuration classes, configure the Spring container (application context), and put the Bean in the configuration class into the container management

  • @Bean : Annotated on the method in the Spring configuration class, registering the bean object to the IOC container

    • name attribute: specify a unique flag for the generated bean

    When the Spring container starts, it automatically scans and executes all methods configured with @Bean, and stores the return value in the Spring container

    Notice:

    • The marked method needs to return an instance
    • The marked method can configure dependent attribute parameters, and Spring will automatically obtain the dependent object from the container and automatically call the method
  • @Primary : In some cases, multiple beans of the same type need to be registered. At this time, @Primary can be used to give a bean a higher priority

  • @ComponentScan : Turn on package scanning (supported by Spring IOC annotations), and scan all classes under the current package and sub-packages by default

    • basePackage attribute: Specifies the scanned package path. can reduce loading time

    If IOC annotations on the class are scanned, the current class will be handed over to the IOC container for management. When the container starts, the object will be automatically created and stored in the container

    If the scan finds that there are DI annotations on the property, inject values ​​into the property according to the rules of dependency injection

  • @PropertySource : Load local properties files to Spring container management

    • value attribute: specify the local properties path
  • @Import : Import the content of other configuration classes in a configuration class

    • value attribute: specify the class class path of other configuration classes

    Spring supports multiple configuration classes (modules of configuration classes). If the configuration class is bloated, you can split the configuration class and then introduce sub-configuration classes into the main configuration class (no configuration annotations are required on sub-configuration classes)

  • @Conditional

    @Condition is a condition judgment function added in Spring 4.0. Through this function, selective creation of Bean operations can be realized.

    @Conditional is marked on the configuration class or on the method of the configuration class. It is used in conjunction with @Configuration. When the conditions specified by @Conditional are met, the content in the configuration class will take effect

    SpringBoot common condition annotations:

    • @ConditionalOnBean : The specified Bean exists in the container

    • @ConditionalOnMissingBean : The specified bean does not exist in the container

      • value attribute: an array of Class objects of the class to be used as the condition
      • type attribute: Name array of the class as the condition (Class.getName())
      • annotation property: the bean has the specified array of annotations
      • name attribute: the name of the bean in the spring container
    • @ConditionalOnProperty : Whether the specified property in the system has the specified value

      • value / name attribute: configuration name, full name or partial name (name and value cannot be used at the same time)

        Can be used with prefix

        You can pass an array to support the combination of multiple conditions (multiple condition logic AND)

        To use multiple conditional ORs:

        • Method 1: Use @ConditionalOnExpression to write "logical or" expressions

          @ConditionalOnExpression("${app.dictionary:false} || ${app.all:false}")
          
        • Method 2: Use @ConditionalOnExpression to write "default value" nested expressions

          @ConditionalOnExpression("${app.dictionary:${app.all:false}}")
          
      • prefix attribute: configuration prefix (optional)

      • havingValue attribute: comparison value, used in combination with name, if the value is the same as the value in the configuration, the configuration will take effect, if not the same, the configuration will not take effect

      • matchIfMissing attribute: whether it can be loaded when this configuration attribute is missing.

        When the configuration is missing, true: load normally, false: report an error. Default is false

    • @ConditionalOnClass : There is a specified class in the system

    • @ConditionalOnMissingClass: The specified class does not exist in the system

    • @ConditionalOnExpression : Satisfy the SpEL expression specification

    • @ConditionalOnSingleCandidate : There is only one specified bean in the container, or this bean is the preferred bean

    • @ConditionalOnResource: Whether the specified resource file exists in the class path

    • @ConditionalOnWebApplication : the current web environment

    • @ConditionalOnNotWebApplication : Currently not a web environment

    • @ConditionalOnJava: Whether the java version of the system meets the requirements


Notes on IOC (container)

  • @Controller : generally marked on the class of the presentation layer (web layer)
  • @Service : Generally marked on the class of the business layer (service layer)
  • @Repository : Generally marked on the class of the persistence layer (dao layer)
  • @Component : component, used on classes that are not in the scope of the three-tier model

Description :

  • Marked on the class that wants to be managed by the IOC container, indicating that the creation of the object is handed over to the container management
  • When the Spring container starts, it automatically scans the IOC annotations according to the package scanning configuration, creates the annotated objects by reflection, stores them in the container, and delegates container management
  • The id (unique identifier) ​​stored in the container by default is the lowercase initials of the current class name. You can customize the id of the object stored in the container through the value attribute

@Import annotation: Import the class into the Spring IOC container

There are many ways to add class to IOC container management, such as @Bean, @Component, etc. @Import is another way, which is faster.

Three methods are supported:

  • Configuration classes with @Configuration (only configuration classes can be imported before version 4.2, and ordinary classes can also be imported after version 4.2)
  • Implementation of ImportSelector
  • Implementation of ImportBeanDefinitionRegistrar

Main usage:

  • Fill in the class array directly

    @Configuration
    @Import({
          
          User.class})   // 大括号中可以添加多个类,使用逗号分隔,例如 {User.class,UserInfo.class}
    public class UserConfig {
          
          }
    
  • ImportSelector method (the bottom layer of Spring Boot uses a lot of methods)

    // 自定义ImportSelector
    public class MyImportSelector implements ImportSelector {
          
          
        @Override
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
          
          
            // 返回的是需要加载的类名数组  注意这里需要的是类的全路径
            return new String[]{
          
          "com.itheima.redis.entity.User"};
        }
    }
    
    @Configuration
    @Import(MyImportSelector.class)
    public class UserConfig {
          
          }
    
  • ImportBeanDefinitionRegistrar method

    This method is similar to the ImportSelector method, but this method can customize the name of the Bean in the container

    // 自定义ImportBeanDefinitionRegistrar
    public class TestImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
          
          
        @Override
        public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {
          
          
            RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(TestD.class);
            //自定义注册bean
            registry.registerBeanDefinition("testD1111",rootBeanDefinition);
        }
    }
    
    @Import({
          
          TestImportBeanDefinitionRegistrar.class})
    @Configuration
    public class ImportConfig {
          
          }
    
  • Note: All three usage methods can be used in one @Import. It should be noted that in the class array method and ImportSelector method, the bean name in the IOC container is the fully qualified class name of the class, while the ImportBeanDefinitionRegistrar method is a custom name

DI (Dependency Injection) related notes

DI annotations are equivalent to directly assigning values ​​​​to attributes without resorting to set methods or constructors

  • @Autowired

    Usage 1: mark on the attribute

    • Assign values ​​directly to properties (through @Autowired dependency injection, no need to configure set methods)
    • The default is to look up the object from the IOC container in the form of by Type (according to the type, that is, the interface type) and inject values ​​into the properties
    • If there are multiple objects of the same type as the attribute in the IOC container (one interface has multiple implementation classes),
      • The default is to find the object from the container according to the attribute name (by Name) as the unique identifier and inject the value into the attribute
      • Can be used together with the @Qualifier annotation to specify a unique flag to find objects from the container and inject values ​​​​to properties
        • value: specifies the unique identifier (id) of the object in the IOC container

    Usage 2: marked on the method

    • Indicates that the current method is automatically executed. If the method has parameters, it will automatically find objects of the same type from the IOC container to pass values ​​to the parameters.
    • You can also add @Qualifier("object id in the IOC container") annotation to the parameter to find the object by name and pass the value to the parameter

    Precautions for use

    1. The @Autowired annotation can only be used in classes managed by the Spring container (annotated with IOC annotations such as @Controller)

    2. Automatic injection has nothing to do with permission modifiers, even private modified fields can be automatically injected

    3. By default, properties automatically injected using the @Autowired annotation must be assembled (Spring container hosting)

      If no bean of this type can be found in the container for injection, an error will be reported

      If it is not allowed to be assembled, you can set the required attribute of @Autowired to false

    4. @Autowired is a type-based injection. If the current type property has only one Bean in the container, the property name is not limited, but it is generally recommended to follow the rule of lowercase first letter of the class name

    5. If the current property type has multiple beans in the container, the Bean name must be specified by the property name or @Qualifier annotation at the same time

  • @Qualifier : When there are multiple beans of the same type, @Qualifier("name") can be used to specify. Can only be used with @Autowired

  • @value : It can be used for injection of simple data types, but it is usually not used in this way. marked on the property.

    Generally used to parse the contents of the properties configuration file or registry configuration file

    • Get the corresponding value according to the key value, syntax rules: @Value(“${key}”)
    • Steps for usage:
      1. The properties configuration file is handed over to the Spring container management
      2. Through @Value, get the configuration item from the container and inject it
  • @Reource (understand)

    Dependency injection annotation provided by jdk, this annotation has been removed in jdk9 and above

    • Can only be marked on the properties of classes managed by the Spring container
    • Indicates to first match the object id in the IOC container according to the attribute name to inject a value into the attribute [by name]
    • If not successful, it will continue to inject values ​​according to the type of the current attribute to match the same type of object in the IOC container [by type]
    • If the name attribute @Resource(name = "object id") is specified, the value can only be injected according to the object id

AOP (method enhancement) related notes

  • @EnableAspectJAutoProxy : marked on the configuration class to enable aop annotation support

  • @Aspect : Annotated on the custom class, declaring the aspect class

    Note: The aspect class also needs to be annotated with IOC annotations (@Component) and handed over to Spring container management

  • Configure the notification type by annotation on the notification (enhancement) method in the aspect class:

    • @Before : pre-advice
    • @AfterReturning : post notification
    • @AfterThrowing : exception notification
    • @After : final notification
    • @Around : Around the notification

    Attributes of notification annotations:

    • value / argNames attribute: pointcut expression or method name annotated by @Pointcut()

      	@Around("pt()")
          public Object around(ProceedingJoinPoint pjp)
      
  • @Pointcut : Annotated on the empty method in the aspect class, extracting the public pointcut expression

    • value/argNames attribute: pointcut expression
    • Notification annotation configuration method name () can introduce public pointcut expressions
        @Pointcut(value="execution(* cn.test.service.impl.*.*(..))")
        public void pt() {
          
          }
    

Notes on transaction management

  • @EnableTransactionManagement : marked on the configuration class to enable transaction annotation support

  • @Transactional : configure transactions

    Common attributes:

    • rollbackFor attribute: Set the exception class array that needs to be rolled back. When an exception in the specified exception array is thrown in the method, the transaction will be rolled back

      • Specify a single exception class: @Transactional(rollbackFor=Exception.class)

      • Specify multiple exception classes: @Transactional(rollbackFor={RuntimeException.class, Exception.class})

    • readOnly attribute: whether to read-only transaction ( true | false (default value) )

    • propagation attribute: transaction propagation behavior ( SUPPORTS | REQUIRED (default value) )

    • transactionManager attribute: When multiple transaction managers are hosted in the Spring container, specify the bean name of the transaction manager

    • isolation attribute: Set the transaction isolation level of the underlying database, which is used to handle the concurrency of multiple transactions

      Usually the default isolation level of the database can be used, and there is basically no need to set it

    • noRollbackFor attribute: Set the exception class array that does not need to be rolled back. When the exception in the specified exception array is thrown in the method, the transaction will not be rolled back

    Labeling position description:

    • Marked on the class: all methods in this class have the same transaction configuration
    • Annotated on the method: the method has a transaction configuration
    • Mark on the class and method at the same time: the principle of proximity (the transaction configuration on the method takes effect)

Notes about the life cycle

  • @Scope : Configure the scope of the object on the class

    Specify the scope (singleton|prototype) through the value attribute, and the default is singleton (singleton)

  • @PostConstruct : The trigger action after the configuration object is created

    When the object is created, the method is automatically executed

  • @PreDestroy : The trigger action before the configuration object is destroyed (only valid when Scope = singleton)

    The method executed before the container is closed and the object is destroyed


Notes about unit testing

  • @RunWith : Set the runner of the unit test, and specify the unit test running environment through the value attribute

    • SpringJUnit4ClassRunner.class: Spring test environment
    • SpringRunner.class : Spring test environment

    Note:

    • SpringRunner extends SpringJUnit4ClassRunner.class

    • SpringRunner and SpringJUnit4ClassRunner can be used with JUnit4.12 or later

      But it is recommended to use SpringRunner, final type, safe

    • Versions below JUnit 4.12 can only use SpringJUnit4ClassRunner

  • @ContextConfiguration : Specifies the configuration information of the container

    • localtions attribute: configuration file path
    • classes attribute: configuration class

Notes on asynchronous calls

  • @EnableAsync : Annotated on the startup class or configuration class to make the @Async annotation take effect

  • @Async : Annotated on an asynchronous pointcut method, indicating that the method is called asynchronously

    When this method is called, it will take a thread from Spring's own thread pool to execute this method instead of using the thread in the web thread pool, so that the thread in the web thread pool can be used to continue to serve other new client requests

    Note :

    • The class where this method resides needs to be managed by the Spring container

    • The modified function should not be defined as a static type, otherwise the asynchronous call will not take effect

    • Return value: If you don’t need a return value, use void directly; if you need a return value, use AsyncResult or CompletableFuture

    • You can specify a custom executor (thread pool), for example: @Async("otherExecutor") (customize a thread pool through @bean)

      • If you use the @Async annotation alone in Spring, you must specify the executor (that is, configure the thread pool), otherwise an error will be reported:

        org.springframework.aop.interceptor.AsyncExecutionAspectSupport getDefaultExecutor

      • In SpringBoot, due to automatic configuration, a SimpleAsyncTaskExecutor thread pool is directly configured by default.

    • The method marked by @Async must be called between different classes: Class A ==> Class B.C method () (@Async is marked on the C method of Class B)

      If it is called in the same class, it will be executed synchronously, for example: Class A.B() ==> Class A.@Async C method ()

      The reason is: the underlying implementation is implemented by the proxy scanning annotations, there is no annotation on the B method, and no corresponding proxy class is generated. (Of course, adding @Async to the class can also solve it, but all methods are asynchronous, which is generally not used!)


Spring MVC Common Annotations

Controller-related

  • @RequestMapping : Used to establish the mapping relationship between the request URL and the processing method, and can also make various restrictions on the request through its attributes

    It can be marked on classes and methods. If it is used on a class, it means that all methods in the class that respond to requests use this address as the parent path.

    Attributes:

    • value / path attribute: specify the request address of the mapping, and the specified address can be a URI Template mode
    • method attribute: specify the method type of the request, GET, POST, PUT, DELETE, etc., example: RequestMethod.post
    • params attribute: Specify the parameters that must be included in the request. If the request does not carry the specified parameters, an exception will be thrown
    • headers attribute: Specifies that the request must contain certain specified header values ​​in order for the method to process the request.
    • consumes attribute: specifies the submitted content type (Content-Type) for processing requests, such as application/json, text/html;
    • produces attribute: specifies the returned content type, and returns only if the (Accept) type in the request request header contains the specified type
  • @RequestParam : Annotated before the Controller method parameters, used to make some restrictions on the common parameters passed in by the url in the request

    Three properties are supported:

    • value / name attribute: default attribute, used to bind the parameter name passed in by the request. It is generally used when the request parameter is inconsistent with the Controller method input parameter
    • required attribute: used to specify whether this parameter must be passed
      • The parameter modified by @RequestParam must pass a value by default, and you can use required = false to specify an optional value
    • defaultValue attribute: specify the default value of the parameter (when the parameter is not required and the request does not pass in the parameter, the default value is used)

    Without @RequestParam annotation:

    • The front-end parameter name needs to be consistent with the variable name of the back-end controller to take effect
    • parameter is optional
  • @PathVariable : placeholder for mapping URL bindings

    URL with placeholder is a new feature of Spring 3.0

    The {xxx} placeholder parameter in the URL can be bound to the input parameter of the controller processing method through @PathVariable("xxx")

    	@RequestMapping("/testPathVariable/{id}")
        public String testPathVariable(@PathVariable("id") Integer id)
        {
          
          
            System.out.println("testPathVariable:"+id);
            return SUCCESS;
        }
    

Global Data Handling (@ControllerAdvice)

  • @ControllerAdvice : Define the global data processing class of the Controller layer. Acts on the controller method annotated with @RequestMapping

    Contains the annotation @Component, which can be scanned

    Generally used with the following annotations

    • @ExceptionHandler (exception handling)
    • @ModelAttribute (data binding)
    • @InitBinder (data preprocessing)
    • **Note:** These three annotations can be used on ordinary Controller classes, and ControllerAdvice only has a scope that can be customized (all by default)

    Support attributes:

    • value / basePackages attribute: Array type, specifying one or more packages, used to specify the base package that can be used

      Will act on the Controller under the specified package and the Controller under its subpackages

      If not specified, defaults to all scanned packages

    • basePackageClasses attribute: It is a variant of basePackages, an array type, specifying one or more Controller classes, and all Controllers under the packages and subpackages of these classes are managed by this @ControllerAdvice

    • assignableTypes attribute: array type, used to specify a specific Controller type, it can be a common interface or parent class, etc.

    • annotations attribute: Specify one or more annotations, the Controller marked by these annotations will be managed by the @ControllerAdvice

  • @RestControllerAdvice : Define the global data processing class of the Controller layer

    Combined annotations, composed of annotations @ControllerAdvice and @ResponseBody

  • @ExceptionHandler : Used to capture different types of exceptions thrown in the Controller

    Often used in conjunction with the @ControllerAdvice annotation to achieve global exception handling

  • @ModelAttribute : The method marked by it will be executed before executing the target Controller method

    Often used in conjunction with the @ControllerAdvice annotation, the global @RequestMapping method can obtain the key-value pairs set here

  • @InitBinder : Used to set WebDataBinder for request data preprocessing


Spring Boot common annotations

  • @SpringBootApplication : combined annotations, usually marked on the startup class

    • @Configuration: Declare this class as a Spring configuration class, and load the beans defined in this class into the Spring container

    • @EnableAutoConfiguration : Automatically load all eligible @Configuration configurations into the current SpringBoot environment

      For example: If you add a spring-boot-starter-web dependency, since it uses Tomcat and Spring MVC, auto-configuration will assume that a web application is being developed and set Spring accordingly.

    • @ComponentScan: Enable package scanning (IOC annotation support), scan all classes under the current package and sub-packages by default

      The scanned package path can be specified through the basePackage attribute to reduce loading time

  • @SpringBootTest : Reading of configuration file properties. Mark on the test class based on running SpringBoot

    • Use SpringBootContextLoader as the default ContextLoader when defined without a specific @ContextConfiguration(loader=…)
    • Automatically search for @SpringBootConfiguration when nested @Configuration is not used, and no explicit class is specified
    • Allows custom environment properties to be defined using the properties attribute
    • Provides support for different webEnvironment modes, including starting a fully running web server listening on a defined or random port.
    • Register a TestRestTemplate or WebTestClient bean for using a fully running web server in web tests
  • @ConfigurationProperties : for auto-configuration bindings

    Support attributes:

    • value / prefix attribute: the prefix of the configuration file configuration item
    • ignoreInvalidFields attribute: the default is false, if the value type does not match, an exception will be thrown
    • ignoreUnknownFields attribute: The default is true, ignoring unknown fields in the object

    Usage 1 : mark on the class, convert the configuration file configuration item into a bean object

    • Notice:
      • Classes annotated with @ConfigurationProperties need to be registered in the spring container in two ways:
        • Method 1: Use @componet and other IOC annotations on classes marked with @ConfigurationProperties annotations
        • Method 2: Mark @EnableConfigurationProperties(bean class name.class) on the class marked with IOC annotations such as @componet or on the configuration class
      • Requires no-argument constructor, getter and setter methods
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Component
    @ConfigurationProperties(prefix = "app.mycar")
    public class Car {
          
          
        private int price;
        private String brand;
    }
    
    @Configuration
    @EnableConfigurationProperties(Car.class) 
    public class Config {
          
          
    }
    

    Usage 2 : Mark on the method of the configuration class, use it with @bean, and bind third-party properties

    @Configuration
    public class DbConfig {
          
          
        @Bean
        @ConfigurationProperties(prefix = "spring.datasource.druid")
        public DataSource datasource(){
          
          
            return new DruidDataSource();
        }
    }
    
  • @EnableConfigurationProperties : Enable the @ConfigurationProperties annotation to take effect and automatically inject this class into the IOC container

    Annotated on classes with IOC annotations such as @componet or on configuration classes

    Support attributes:

    • value attribute: Class<?>[] array, that is, the Class array of the class annotated with @ConfigurationProperties annotation

Spring Cloud Common Annotations

Service Registration / Service Discovery / Configuration Center

  • @EnableEurekaClient : Enable service registration and service discovery

    Based on spring-cloud-netflix, if the selected registration center is eureka, it is recommended to use this annotation

  • @EnableDiscoveryClient : Enable service registration and service discovery

    Based on spring-cloud-commons, if it is another registration center, it is recommended to use this annotation

  • @EnableEurekaServer : Annotate the startup class or configuration class to identify the service as the eureka server

  • @EnableConfigServer : Annotate the startup class or configuration class to identify the service as the service center server

  • @RefreshScope : Annotated on the class to automatically refresh the data obtained from the configuration center

    Only by adding this annotation, when the data in the configuration center is refreshed, the object of this class will be automatically reloaded, and the automatically updated data will be injected into @value


Feign components

  • @EnableFeignClients : Enable Feign annotations. Marked on the startup class or configuration class

    When the project starts, a FeignSterter component will be started, which will create proxy objects for classes that use @FeignClient in the project

  • @FeignClient : declare that this is a Feign client, and specify the service name through the name / value attribute

    • It can only be marked on the interface called by the remote service

      (The FeignClient annotation is modified by @Target(ElementType.TYPE), indicating that the target of the FeignClient annotation is on the interface)

    • When SpringCloud scans the interface identified by @FeignClient, the bottom layer will create an implementation class proxy object (jdk proxy) for it, and hand it over to the spring container management (register IOC container); the name of the created Bean object is specified by the name or value attribute of the annotation. If two remote service call interfaces are created for the same service, an error will be reported

    • The methods defined in the interface fully use SpringMVC annotations, Feign will generate URLs according to the annotations, and access the results

    • The startup class or configuration class of the service needs to be marked with the @EnableFeignClients annotation to make Fegin take effect

    Common attributes of the @FeignClient annotation are as follows:

    • name / value attribute: Specify the name of FeignClient. If the project uses Ribbon (registration center), the name attribute will be used as the name of the microservice for service discovery

    • url attribute: generally used for debugging, you can manually specify the address called by @FeignClient. empty by default

      • The url can be obtained from the configuration file, if there is, it will be called through the url, if not, it will be called according to the service name.

        format isurl = "${xxx.xxx.xxx: }"

    • configuration attribute: Feign configuration class, you can customize Feign's Encoder, Decoder, LogLevel, Contract, and you can specify different configurations for each feign client

    • fallback attribute: defines the fault-tolerant processing class. When the call to the remote interface fails or times out, the fault-tolerant logic of the corresponding interface will be invoked. The class specified by fallback must implement the interface marked by @FeignClient

    • fallbackFactory attribute: factory class, used to generate fallback class examples, through this attribute, the common fault-tolerant logic of each interface can be realized, and duplication of code can be reduced

    • path attribute: Define the unified prefix of the current FeignClient, used when server.context-path, server.servlet-path are configured in the project

    • decode404 attribute: When an http 404 error occurs, if the field is true, the decoder will be called for decoding, otherwise a FeignException will be thrown


other notes

  • @LoadBalanced : Enable Ribbon load balancing function

    Add a LoadBalancerClient to RestTemplate to achieve client load balancing through Ribbon

    • Annotated on the RestTemplate object, provided by SpringCloud's commons module

    Principle: When using the RestTemplate object to call a service, the bottom layer of the system will intercept the service. After intercepting the url, it will obtain a specific service instance based on the service name of the url, then reconstruct the url based on the service instance, and then make a service call based on the new url

  • @EnableCircuitBreaker : Turn on the circuit breaker function

  • @EnableHystrixDashboard : mark the startup class or configuration class, identify the service as the Hystrix-Dashboard service (dashboard), and monitor the traffic of the server

  • @EnableTurbine : mark the startup class or configuration class to identify the service as a Turbine service, and monitor the traffic of multiple servers at the same time

  • @EnableZuulProxy : Use this annotation in the main startup class or configuration class to identify the service as a Zuul gateway service


Common annotations for lombok

  • @Data : Annotated on the class; provide getter, setter, equals, canEqual, hashCode, toString methods

  • @Setter : Annotated on the property; provide a setter method for the property

  • @Getter : Annotated on the property; provide a getter method for the property

  • @NoArgsConstructor : Annotated on the class; provide a parameterless constructor for the class

  • @AllArgsConstructor : Annotated on the class; provide a full parameter constructor for the class

  • @EqualsAndHashCode : implement equals() method and hashCode() method

  • @ToString : Implement the toString() method

  • @Slf4j : Annotated on the class; provide a log4j log object with an attribute named log for the class

    slf4j is an adapter, when the application changes a log source, there is no need to change the code

  • @Log4j : Annotated on the class; provide the class with a log object with an attribute named log

    log4j is a product that truly implements the logging function

  • @Cleanup : close the stream

  • @Synchronized : object synchronization

  • @SneakyThrows : throws an exception

Guess you like

Origin blog.csdn.net/footless_bird/article/details/128704278
Recommended