@Target

  • Function: Specifies the scope of the embellished annotation. Where can the described annotation be used

    @Target(ElementType.Type)
  • The type of elementType value:

    • Type: Class, interface, or enumeration
    • Field: Field containing the enumeration constants
    • METHOD: the METHOD
    • PARAMETER: PARAMETER
    • CONSTRUCTOR: CONSTRUCTOR
    • LOCAL_VARIABLE: Local variable
    • ANNOTATION_TYPE: Annotation_type
    • PACKAGE: a PACKAGE

      @Retention

  • Function: Specifies the life cycle of the embellished annotation, i.e. the stage to which it will be retained
  • There are three types of RetentionPolicy values:

    • Source: Reserved at the SOURCE level, discarded after compilation
    • CLASS: Reserved at the compile level. It exists in the compiled CLASS file and is discarded during JVM runtime. This is the default value
    • Runtime: The RUNTIME level is reserved, exists in the compiled class file, remains in the JVM while it is running, and can be invoked by reflection

      @Documented

  • What it does: Specifies embellished annotations that can be documented by tools such as Javadoc

    • I’m only responsible for marking
    • No member values

      @Inherited

  • Action: Allows a subclass to inherit annotations from its parent class
  • @inherited needs to be used with @aliasFor: @aliasFor is used on the attributes that correspond to the child annotations

    • Annotations are inheritable, but they do not inherit attributes from the parent annotation
    • That is, the attribute value of the annotation at class scan time is still the attribute value of the parent annotation, not the attribute value of the custom annotation
    • You need to use @AliasFor on the attributes of the annotation

      @ComponentScan

  • Role: Define the scan path to identify the classes that need to be assembled and automatically assemble them into Spring’s bean container
  • By default, all configuration classes under the package in which the class resides are scanned
  • Parameter types in @ComponentScan:

    • Value: Used to scan the path of the specified packet
    • BasePackages: Specifies the path of the package to be scanned, just like value. Value is recommended
    • BasePackageClasses: Used to scan the path of the package that specifies the class
    • NameGenerator: Used to name the detected bean component in the Spring container
    • UseDefaultFilters: Are @Component,@Repository,@Service,@Controller classes on or off
    • ExcludeFilters: Excludes according to filter conditions

      • FilterType.annotation: Follow the ANNOTATION
      • FILTERTYP.ASSIGNABLE_TYPE: As per the given type
      • FilterType.AspectJ: Use AspectJ expressions
      • FilterType.regex: Use regular expressions
      • FilterType.custom: Follow the CUSTOM rules
    • IncludeFilters: Includes according to filter criteria

      • FilterType.annotation: Follow the ANNOTATION
      • FILTERTYP.ASSIGNABLE_TYPE: As per the given type
      • FilterType.AspectJ: Use AspectJ expressions
      • FilterType.regex: Use regular expressions
      • FilterType.custom: Follow the CUSTOM rules

        @Filter

  • Role: Filter annotations that configure filter conditions
  • Parameter types in @Filter:

    • type
    • class

      @interface

  • Function: Custom annotations
  • Automatically inherit the Java. Lang. The annotation. The annotation interface, the compiler automatically other details
  • When you define an annotation, you cannot inherit from another annotation or interface
  • @interface is used to declare an annotation:

    • Each of these methods actually declares a configuration parameter
    • The name of the method is the name of the parameter
    • The return value type of the method is the type of the parameter
    • The return value type can only be basic,Class,String, and enum
    • Default can be used to declare the default value of a parameter
  • Define the format of the annotations:

    Public @Interface annotation name {body}
  • Data types supported by annotation parameters:

    • Basic data types: int, float, Boolean, byte, double, char, long, short
    • Type String
    • The Class type
    • Enum type
    • The Annotation type
    • An array of combinations of the above types
  • Parameter setting rules for the Annotation type:

    • Can only be modified with public or default access:
    • Parameter members can only use basic types of byte, short, char, int, long, float, double, Boolean eight basic data types, and String, Enum, Class, annotations and other data types, and that some types of arrays
    • If there is only one parameter member, it is best to set the parameter name to value followed by braces
  • Default values for annotation elements:

    • Annotation elements must have definite values
    • Specified either in the default value where the annotation is defined or when the annotation is used. The value of an annotation element of a non-primitive type cannot be NULL
    • So use an empty string or 0 as the default constraint
  • This constraint makes it difficult for the processor to represent the presence or absence of an element:

    • Because in the declaration of each annotation, all elements exist and all have corresponding values
  • To get around this constraint, only special values (such as an empty string or a negative number) can be defined to indicate that an element does not exist

    @AliasFor

  • Function: Adds an alias name to the attribute of the annotation
  • Within the same annotation, aliases are used for two different attributes:

    • No matter which property name you set the property value for, the other property name will also have the same property value
    • The value of each alias property must be the same, otherwise an error will be reported
    • Attributes must have default property values
Public @interface requestMapping {@aliasFor ("path") // Path [] value() default {}; @aliasFor ("value") // Path and value must be the same, otherwise we will return an error String[] path() default {}; }
  • Explicitly override attributes in meta annotations:

    • Explicitly aliases the properties of a meta annotation
    • Property type. The default value of the property must be the same
    • @AliasFor can only alias a meta annotation that is the current annotation
  • Example:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = AopConfig.class)
    public class AopUtilsTest {}

    To replace the @ContextConfiguration(classes = aopconfig.class) annotation, define a tag like this:

    @Retention(RetentionPolicy.RUNTIME) @ContextConfiguration public @interface Context { @AliasFor(value = "classes", annotation = ContextConfiguration.class) Class<? >[] cs() default {}; }
  • Because the @ContextConfiguration annotation itself is defined as @Inherited, the Context annotation is understood to inherit the @ContextConfiguration annotation
  • The cs property is equivalent to the classes property in the @ContextConfiguration property. The @aliasfor tag is used, set separately:

    1. Value: As an alias for the attribute
    2. Annotation: An alias for which annotation

Use the Context tag to achieve the same effect:

@RunWith(SpringJUnit4ClassRunner.class)
@STC(cs = AopConfig.class)
public class AopUtilsTest {}
  • To declare an alias implicitly in a comment:

     @ContextConfiguration
     public @interface MyTestConfig {
    
      @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
      String[] value() default {};
    
      @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
      String[] groovyScripts() default {};
    
      @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
      String[] xmlFiles() default {};
     }

    This is an implicit alias declaration in a unified annotation:

  • In MyTestConfig annotation, the value, groovyScripts xmlFiles are defined as @ AliasFor (annotation = ContextConfiguration. Class, Attribute = “locations”)
  • In this annotation, Value, GroovyScripts, and XMLFiles are also aliases to each other
  • Passing an alias:

    • The @AliasFor annotation allows passing between aliases:

      • If A is an alias for B and B is an alias for C, then A is an alias for C

        @MyTestConfig
         public @interface GroovyOrXmlTestConfig {
        
        @AliasFor(annotation = MyTestConfig.class, attribute = "groovyScripts")
        String[] groovy() default {};
        
        @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
        String[] xml() default {};
         }
  • GroovYorXMLTestConfig uses @MyTestConfig as a meta-annotation
  • The Groovy property is defined and aliases the GroovyScripts property in MyTestConfig
  • An XML attribute is defined and used as an alias for the locations property in ContextConfiguration
  • Because the groovyScripts property in myTestConfig is itself an alias to the locations property in ContextConfiguration, the XML property and the groovy property are aliases to each other as well
  • Properties in @alias:

    • Annotation: class type, the type of the class to which the alias attribute belongs
    • Attribute: An attribute that requires an alias
    • Value: The alias name of the property

      @Import

  • @import supports importing a normal Java class and declaring it as a Bean
  • @import usage scenario:

    • The @import is primarily used during the explicit creation of beans based on Java code
    • @import is used to merge multiple discrete Java Config configuration classes into a single full Config class
  • Composition of configuration classes occurs primarily in cross-module or cross-package configuration class references: multiple configuration files by function or by business are imported into a single configuration file, avoiding writing all the configurations in one configuration
  • The @Import annotation is similar to the @ImportResource annotation
  • Use @importResource and @Value to read resource files

    SpringBoot

    @SpringBootApplication

  • Contains:

    • @Configuration
    • @EnableAutoConfiguration
    • @ComponentScan
  • Usually used on the main class

    @ConfigurationProperties

  • You can use @ConfigurationProperties to get the parameter values for a number of parameters configured in Application.properties and Application.yml
  • Use of @ConfigurationProperties: To provide a class with a field for each captured external property

    • The associated external properties defined by the prefix prefix are bound to the fields of the class
    • According to SpringBoot’s loose binding rules, the name of a class property must match the name of an external property

      • You can inject methods from a bean of class type using the @Bean annotation into another bean, so that the bean can access externally configured parameter values in a type-safe manner
    • You can define a default value by simply initializing a field with a value. Preferably the same value as in the configuration file
    • The class itself can be package private
    • The fields of the class must have public setter methods
  • Activate the @ ConfigurationProperties:

    • Make ComponentScan scan by adding the @Component annotation
    • This only takes effect if the package in which the class resides is scanned by Spring’s @ComponentScan. By default, this annotation scans all package structures under the main application class

      @Component
      @ConfigurationProperties(prefix = "spring.logger")
      class LogProperties {
        ...
      }
    • Activate @ConfigurationProperties through Spring’s Java Configuration feature
    • As long as the MailModuleProperties class is scanned by the SpringBoot application, the MailModuleProperties bean can be accessed in the application context

      @Configuration class PropertiesConfig { @Bean public LogModuleProperties logModuleProperties() { return new logModuleProperties(); }}
      • At the same time you can use @ EnableConfigurationProperties makes SpringBoot find this class. This annotation in the @ Import (EnableConfigurationPropertiesImportSelector. Class)

        @Configuration
        @EnableConfigurationProperties(LogModuleProperties.class)
        class PropertiesConfig {
        }

        When activating an @ConfigurationProperties class, it is best to modularize the application and have each module provide its own @ConfigurationProperties class, providing only the properties required by the module. This makes it easier to refactor properties in one module without affecting other modules. So in a program is not recommended to use the @ EnableConfigurationProperties class itself, should be in a specific module to use the @ EnableConfigurationProperties @ the Configuration class, The class can also take advantage of the package’s private visibility to hide properties from the rest of a particular application

  • Attributes that cannot be converted in @ConfigurationProerties:

    • When you configure the wrong value for the property in @ConfigurationProperties, you do not want the SpringBoot application to fail to start. The ignoreInvalidFields annotation property can be set to true and false by default

      @ConfigurationProperties(prefix = "spring.logger", ignoreInvalidFields = true)
      public class LogModuleProperties {
      private Boolean enabled = Boolean.True;
      }

      SpringBoot will set the enable field to its default value. If the default is not set, the enabled value will be null because the wrapper class Boolean is defined here

  • Unknown property in @ConfigurationProperties:

    • By default,SpringBoot ignores properties that cannot be bound to fields of the @ConfigurationProperties class
    • When yet another property in the configuration file is not actually bound to the @ConfigurationProperties class, you want SpringBoot to fail to start
    • Or you have used the property before, but it has been deleted, and you want to be told to remove the property manually from application.properties
    • The ignoreUnknownFields attribute is set to false, which is true by default

      @ConfigurationProperties(prefix = "spring.logger", ignoreUnknownFields = false)
      class LogModuleProperties {
      private Boolean enabled = Boolean.TRUE;
      private String defaultSubject;
      }

      for
      ignoreUnkownFields,In SpringBoot there may be two classes with @ConfigurationProperties that are bound to the same namespace
      (namespace)On, one of the classes may know about a property while the other does not, resulting in a boot failure. So this property is no longer used

  • Verify @ConfigurationProperties on startup:

    • If you want the configuration parameters to be valid when passed into the application, you can do so by adding the Bean Validation annotation on the fields and the @ VALIDATED annotation on the classes

      @ConfigurationProperties(prefix = "spring.logger") @Validated @Data class LogModuleProperties { @NotNull private Boolean  enabled; @NotEmty private String defaultSubject; }

      If the default validation annotations do not meet the validation requirements, you can customize the annotations. If the validation logic is special, you can implement a method with the @PostConstruct flag, and if validation fails, the method throws an exception

  • Complex attribute type:

    • Most of the time, the arguments passed to the application are basic strings or numbers, and sometimes you need to pass data types such as List
    • The List and Set:

      • There are two ways for SpringBoot to automatically populate the List property:

        • Write as an array in the application.properties file

          spring.logger.smtpServers[0]=server1
          spring.logger.smtpServers[1]=server1
        • Application.yml itself supports the List type, which can be added to the Application.yml file

          spring:
            mail:
                smtpServers:
                    - server1
                    - server2
      • The set collection is configured in the same way
    • It is recommended to use YML for data configuration, which can be better read and structured
  • Duration:

    • SpringBoot has built-in support for resolving duration from configuration parameters:

      @Data
      @ConfigurationProperties(prefix = "spring.logger")
      class loggerModuleProperties {
        private Duration pauseBetweenLogs;
      }
    • You can configure either the millisecond value or the text with units:

      spring.logger.pause-between-logs=5s
    • If duration is configured with no write units, it is specified in milliseconds by default. You can also specify units via @durationUnit:

      @Data
      @ConfigurationProperties(prefix = "spring.logger")
      class loggerModuleProperties {
        @DurationUnit(ChronoUnit.SECONDS)
        private Duration pauseBetweenLogs;
      }
    • Common units are as follows:

      • Ns: NANOSECONDS – NANOSECONDS
      • US: Microseconds – MICROSECONDS
      • MS: MILLISECONDS – MILLISECONDS
      • S: SECONDS – SECONDS
      • M: you can – points
      • H: HOURS –
      • D: DAYS – DAYS
  • DataSize:

    • As with Duration, the default unit is byte, which can be specified with the @DataSizeUnit unit

      @Data
      @ConfigurationProperties(prefix = "spring.logger")
      class loggerMailModuleProperties {
        @DataSizeUnit(DataUnit.MEGABYTES)
        private DataSize maxAttachmentSize = DataSize.ofMegebytes(2);
      } 
    • Add configuration:

      spring.logger.max-attachment-size=1MB

      The output is shown in units of B(bytes)

    • Common units are as follows:

      • B: BYTES
      • KB: KILOBYTES
      • MB: MEGEBYTES
      • GB: GIGABYTES
      • TB: TERABYTES
  • Custom type:

    • Sometimes you want to parse configuration parameters to a custom object type, such as a custom item weight:

      spring.logger.max-attachment-weight=5kg
    • Add Weight attribute to MailModuleProeprties:

      @Data
      @ConfigurationProperties(prefix = "spring.logger")
      class MailModuleProperties {
        private Weight maxAttachmentWeight;
      }
    • Creating a Custom Converter

      class WeightConverter implements Convert<String, Object> {@Override public Weight convert(String source) {// create and return an Object of type Weight from a String source}}
    • Register the custom converter with the SpringBoot context

      @Configuration
      class PropertiesConfig {
        @Bean
        @ConfigurationPropertiesBinding
        public WeightConverter weightConverter() {
            return new WeightConverter();
        }
      }

      @ ConfigurationPropertiesBinding annotation is to let SpringBoot use the converter to do the data binding

  • The tag configuration property is Deprecated:

    @DeprecatedConfigurationProperty(reason = "change name", replacement = "none")
    public String getDefaultSubject() {
      return defaultSubject;
    }

    Can add @ DeprecatedConfigurationProperty annotations on field getter methods, to mark this field is deprecated

  • SpringBoot’s @ConfigurationProperties annotation is very powerful when binding type-safe Java beans
  • Can cooperate with the annotation properties and @ more modular DeprecatedConfigurationProperty annotations for configuration
  • If you use a SpEL expression, you can only select the @Value annotation

    @Repository

  • Used to annotate data access components, namely DAO components

    @Service

  • Used to annotate business layer components

    @RestController

  • Used to annotate control layer components
  • Contains:

    • @Controller
    • @ResponseBody

      @Controller

  • Used to annotate control layer components
  • Use @Controller instead of @RestController when you need to return to the page

    @ControllerAdvice

  • Used to define @ExceptionHandler, @InitBinder, and @ModelAttribute, and applied to all @RequestMapping

    • @initbinder: Initialize the data binder before execution
    • @ModelAttribute: Binding a value to the Model allows you to retrieve the value
    • @ExceptionHandler: Global exception capture handling

      @Component

  • Referring to the component
  • This annotation can be used to indicate when components cannot be classified

    @ResponseBody

  • Indicates that the return result of this method is written directly to the HTTP Response Body

    • Typically used when retrieving data asynchronously
  • After using @RequestMapping, the return value is usually resolved as a jump path
  • Such as:

    • After adding @responseBody, the result is not parsed as a jump path, but written directly to the HTTP ResponseBody
    • Get the JSON data asynchronously, and if you add @responseBody, it will return the JSON data directly

      @RequestBody

  • The comment in front of the parameter indicates that the parameter is required
  • Receive a JSON string as a List object

    @ComponentScan

  • The component scanning
  • Classes that are scanned with @Component, @Cotroller, @Service, etc. annotations are registered as beans *

    @Configuration

  • Indicates that the class is the source of information for the Bean
  • The equivalent of XML, usually annotated on the main class

    @ConditionOnProperty

  • The control Configuration takes effect when the condition holds
  • Properties:

    • Value: array, get the name of the corresponding property, and name cannot be used at the same time
    • Prefix: The prefix to the property name, optional or not
    • Name: An array with the full name or part of the property name (combined with prefix to form the full property name). It cannot be used with value
    • HavingValue: It can be used in combination with Name to compare whether the obtained attribute value is the same as the value given by HavingValue. The configuration is loaded only when the same value is obtained
    • MatchMissing: Whether the property can be loaded if it is missing. If true, it will load normally without the property. If false, an error will be reported without the property, which is false by default
    • RELAXEDNAMES: Whether loose matching is supported

      @Bean

  • As in XML, the annotation is on the method
  • Generates a bean and gives it to Spring to manage

    @EnableAutoConfiguration

  • Make SpringBoot configure the Spring framework based on the dependencies declared by the application
  • Usually added to the main class

    @Autowired

  • ByType way
  • Use the configured beans to complete the assembly of properties and methods
  • Class members, methods, and constructors can be annotated for auto-assembly
  • If @Autowired(required = false) is added, it will not report an error if the bean cannot be found

    @Qualifier

  • When there are multiple beans of the same type, you can specify this using @Qualifier(“name”)
  • It needs to be used with @Autowired

    @Resource

  • @Resource(name = “name”, type = “type”)
  • If there is no property, the default is ByName, similar to the @Autowired function

    @RequestMapping

  • @RequestMapping is an annotation that handles request address mapping. It can be used on a class or method
  • When used on a class, all methods in the class that respond to requests have that address as the parent path
  • @RequestMapping has six properties:

    • Params: Specifies that some parameter values must be included in the request for the method to process the request
    • HEADERS: Specifies that some specified header value must be included in the request for the method to handle the request
    • Value: Specifies the actual address of the request. The address specified can be the URI Template pattern
    • Method: Specifies the type of method requested, such as GET, POST, PUT,DELETE, etc
    • Consumes: Specifies the Type of the Content that is submitted to handle the request, -Content-Type. Such as: application, json, text, HTML
    • Produces: Specifies the content type to be returned, returned only if the specified type is included in the (Accept) type in the request header

      @GetMapping

  • @getmapping, @postmapping are composite annotations
  • @RequestMapping(value = “/”, method = RequestMethod.Get(POST, PUT, DELETE))

    @RequestParam

  • Used before an argument to a method
  • Equivalent to the request. The getParameter

    @PathVariable

  • Path variable: requestMapping (“user/get/ MAC /{macAddress}”)

    public String getByMacAddress(@PathVariable("macAddress") String macAddress) {}

    If the parameter is the same as the name in the braces, the content in the braces after the comment can be left out

    Global exception handling

    @ControllerAdvice

  • Contains @ Component
  • It can be scanned
  • Unified Exception Handling

    @ExceptionHandler

  • @Exceptionhandler(Exception.class)

    • When used on a method, the method is executed when the exception is encountered

      SpringCloud

      @EnableEurekaServer

  • Used on SpringBoot boot classes
  • Indicates that this is an Eureka service registry

    @EnableDiscoveryClient

  • Used on SpringBoot boot classes
  • Indicates that this is a service that can be found by the registry

    @LoadBalanced

  • Enable load balancing capability

    @EnableCircuitBreaker

  • Used on SpringBoot boot classes
  • Open circuit breaker function

    HystrixCommand

  • @HystrixCommand(fallbackMethod = “backMethod”)
  • FallbackMethod specifies the breakback callback method

    @EnableConfigServer

  • Used on SpringBoot boot classes
  • To indicate that this is a configuration center, open Config Server

    @EnableZuulProxy

  • Used on SpringBoot boot classes
  • The Zuul route is enabled

    @SpringCloudApplication

  • A collection of microservice annotations, including:

    • @ SpringBootApplication: SpringBoot annotation
    • EnableDiscoveryClient: Registration Service Center Eureka annotated
    • @enablecircuitbreaker: Comments on circuit breakers
  • This is a must for every microservice