This is the 21st day of my participation in Gwen Challenge

@Target

  • Purpose: specify the scope of use of the annotation that modifies, i.e. where can the annotation described be used
@Target(ElementType.Type)
Copy the code
  • ElementType Specifies the type of the value:
    • TYPE: class, interface, or enumeration
    • FIELD: a FIELD containing enumerated constants
    • METHOD: the METHOD
    • PARAMETER: PARAMETER
    • (4) CONSTRUCTOR
    • LOCAL_VARIABLE: local variable
    • ANNOTATION_TYPE: Annotation type
    • PACKAGE: a PACKAGE

@Retention

  • Role: Indicates the lifetime of the embellished annotations, i.e., to which stage they will remain
  • RetentionPolicyThere are three value types of:
    • SOURCE: retained at the SOURCE level and discarded after compilation
    • CLASS: retained at the compile level, present in the compiled CLASS file and discarded at JVM runtime, which is the default
    • RUNTIME: run-level reserved, present in the compiled class file, retained at JVM RUNTIME and can be called by reflection

@Documented

  • Function:A note specifying embellishment, which can be used for examplejavadocThis type of tool documentation
    • Just marking
    • No member value

@Inherited

  • What it does: Allows a subclass to inherit an annotation from its parent class
  • Inherited When used with @Aliasfor:Use @aliasfor for the attribute corresponding to the child annotation
    • Annotations can be inherited, but annotations cannot inherit properties of their parent annotations
    • 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 attribute of the annotation

@ComponentScan

  • What it does: Define a path to scan for classes that identify the classes that need to be assembled automatically into Spring’s bean container
  • By default, all configuration classes in the package in which the class resides are scanned
  • Parameter types in @ComponentScan:
    • Value: used to scan the path of the specified packet
    • BasePackages: used to specify the path of packets to be scanned, the same as value. Value is recommended.
    • BasePackageClasses: Scans the path of the package that specified a class
    • NameGenerator: Used to name detected bean components in the Spring container
    • UseDefaultFilters: Specifies whether to enable detection for the @Component, @repository, @service, and @Controller classes
    • excludeFilters:Exclude according to filtering conditions
      • Filtertype. ANNOTATION: Follow the ANNOTATION
      • Filtertype. ASSIGNABLE_TYPE: based on the given type
      • Filtertype. ASPECTJ: Uses ASPECTJ expressions
      • Filtertype. REGEX: uses regular expressions
      • Filtertype. CUSTOM: according to CUSTOM rules
    • includeFilters:Include according to filter conditions
      • Filtertype. ANNOTATION: Follow the ANNOTATION
      • Filtertype. ASSIGNABLE_TYPE: based on the given type
      • Filtertype. ASPECTJ: Uses ASPECTJ expressions
      • Filtertype. REGEX: uses regular expressions
      • Filtertype. CUSTOM: according to CUSTOM rules

@Filter

  • Effect: Sets filter annotations for filter criteria
  • 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 defining annotations, you cannot inherit from other annotations or interfaces
  • @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 a method is the type of the parameter
    • The return value type can only be the basic type,Class,String, or enum
    • You can declare default values for parameters with default
  • Define the format of the annotations:
public @interfaceAnnotation name {definition body}Copy the code
  • Annotation parameters support data types:
    • Basic data types: int, float, Boolean, byte, double, char, long, short
    • Type String
    • The Class type
    • Enum type
    • The Annotation type
    • An array composed of the above types
  • Parameter setting rules in Annotation type:
    • Can only be qualified with public or default 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 parentheses
  • Default values for annotation elements:
    • The annotation element must have a definite value
    • The value of an annotation element that is not a primitive type cannot be NULL, either specified in the default value of the annotation definition or when the annotation is used
    • So use an empty string or 0 as the default constraint
  • This constraint makes it difficult for the processor to represent an elementPresence or absenceThe status of:
    • Because in each annotation declaration, all elements are present and have corresponding values
  • To get around this constraint, only special values (such as empty strings or negative numbers) can be defined to indicate that an element does not exist

@AliasFor

  • Effect: Adds an alias to an attribute of the annotation
  • To alias two different attributes together in the same annotation:
    • Whichever attribute name you set the value for, the other attribute name is the same attribute value
    • The alias attributes must have the same value; otherwise, an error will be reported
    • Properties must have default property values
public @interface RequestMapping {
   
    @AliasFor("path") 			// In this case, the path and value values must be the same; otherwise, an error will be reported
    String[] value() default {};

    @AliasFor("value") 			// In this case, the path and value values must be the same; otherwise, an error will be reported
    String[] path() default {};
    
}
Copy the code
  • Explicitly override attributes in meta-annotations:
    • Explicitly alias the properties of the meta-annotation
    • Attribute type. The default value of the attribute must be the same
    • @aliasfor can alias only meta annotations that are the current annotation
  • Example:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AopConfig.class)
public class AopUtilsTest {}
Copy the code

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 {};
}
Copy the code
  1. The @ContextConfiguration annotation itself is defined as @ContextConfiguration, so Context annotations are understood to inherit @ContextConfiguration
  2. csAttribute is equivalent to@ContextConfigurationProperties of theclassesProperty@AliasForTags, set separately:
    1. Value: alias for which attribute
    2. Annotation: Alias as which annotation

Using the Context tag can do the same:

@RunWith(SpringJUnit4ClassRunner.class)
@STC(cs = AopConfig.class)
public class AopUtilsTest {}
Copy the code
  • To implicitly declare an alias 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 {};
 }
Copy the code

This is implicitly declaring aliases in uniform annotations:

  1. In MyTestConfig annotation, the value, groovyScripts xmlFiles are defined as @ AliasFor (annotation = ContextConfiguration. Class, Attribute = “locations”) alias
  2. In this annotation,value,groovyScripts, and xmlFiles are also aliases to each other
  • Alias passing:
    • The @aliasfor annotation allows passing between aliases:
      • If A is an alias of B and B is an alias of C, then A is an alias of C
@MyTestConfig
 public @interface GroovyOrXmlTestConfig {

    @AliasFor(annotation = MyTestConfig.class, attribute = "groovyScripts")
    String[] groovy() default {};

    @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
    String[] xml() default {};
 }
Copy the code
  1. GroovyOrXmlTestConfig makes @myTestConfig a meta-annotation
  2. The Groovy property is defined as an alias to the groovyScripts property in MyTestConfig
  3. XML properties are defined as aliases for locations properties in ContextConfiguration
  4. Because the groovyScripts property in MyTestConfig is itself an alias for the Locations property in the ContextConfiguration, the XML and Groovy properties are also aliases for each other
  • Attributes in @alias:
    • Annotation: Class type. The class type of the alias property. That is, which annotation class the alias property belongs to
    • Attribute: The attribute that needs an alias
    • Value: alias of the property

@Import

  • @import supports importing a normal Java class and declaring it as a Bean
  • @import Usage scenario:
    • @import is primarily used in the process of explicitly creating beans based on Java code
    • @import is used to merge multiple discrete Java Config configuration classes into a complete Config class
  • The combination of configuration classes mainly occurs during cross-module or cross-package configuration class reference. Import multiple configuration files divided by function or service into a single configuration file, avoiding writing all configurations into one configuration file
  • The @import annotation is similar to the @importResource annotation
  • Resource files can be read using @importResource and @Value

SpringBoot

@SpringBootApplication

  • Contains:
    • @Configuration
    • @EnableAutoConfiguration
    • @ComponentScan
  • Usually used with the main class

@ConfigurationProperties

  • You can use @ConfigurationProperties to get parameter values for a number of parameters configured in application.properties and application.yml
  • ConfigurationProperties:Provide a class with a field for each captured external property
    • The related external attributes defined by prefix are bound to the fields of the class
    • According to SpringBoot’s lax binding rules, the name of a class property must match the name of an external property
      • A bean of class type can be injected into another bean using the @Bean annotation method, and that 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
    • Fields of a class must have public setter methods
  • Activate the @ ConfigurationProperties:
    • Make ComponentScan scan by adding the @Component annotation
    • This class takes effect only if the package in which it 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 {... }Copy the code
    • Enable @ConfigurationProperties through Spring’s Java Configuration feature
    • As soon as the MailModuleConfiguration class is scanned by the SpringBoot application, the MailModuleProperties Bean can be accessed in the application context
    @Configuration
    class PropertiesConfig {
    	@Bean 
    	public LogModuleProperties logModuleProperties(a) {
    		return newlogModuleProperties(); }}Copy the code
  • 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 {}Copy the code

It is best to modularize your application when activating an @ConfigurationProperties class and have each module provide its own @ConfigurationProperties class that provides only the properties the module needs. 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, This class can also take advantage of package-private visibility to hide properties from the rest of a particular application

  • Untransformable properties in @configurationProerties:
    • You don’t want the SpringBoot application to fail to start when you configure the wrong value for the @ConfigurationProperties property. The ignoreInvalidFields attribute can be set to true, and the default is false
@ConfigurationProperties(prefix = "spring.logger", ignoreInvalidFields = true)
public class LogModuleProperties {
	private Boolean enabled = Boolean.True;
}
Copy the code

SpringBoot will set the enable field to the default value. If the default is not set, the value of Enabled will be null, because Boolean’s wrapper class Boolean is defined here

  • Unknown properties in @configurationProperties:
    • By default,SpringBoot ignores properties that cannot be bound to the @ConfigurationProperties class field
    • Expect SpringBoot to fail when another property in the configuration file is not actually bound to the @ConfigurationProperties class
    • Or you have used the property before, but it has been removed, and want to be triggered to tell you to manually remove the property from application.properties
    • This requires setting the ignoreUnknownFields attribute to false, which is true by default
@ConfigurationProperties(prefix = "spring.logger", ignoreUnknownFields = false)
class LogModuleProperties {
	private Boolean enabled = Boolean.TRUE;
	private String defaultSubject;
}
Copy the code

For ignoreUnkownFields, It is possible to have two classes with @ConfigurationProperties in SpringBoot that are bound to the same namespace. One class may know about a property and the other does not, resulting in a boot failure. So this property is no longer used

  • ConfigurationProperties:
    • If you want the configuration parameters to be valid when passed into the application, you can annotate the bean Validation on the field and add the @validated annotation on the class
@ConfigurationProperties(prefix = "spring.logger")
@Validated
@Data
class LogModuleProperties {
	@NotNull private Boolean enabled;
	@NotEmty private String defaultSubject;
} 
Copy the code

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 marked @postconstruct and throw an exception if the validation fails

  • Complex attribute types:
    • In most cases, the arguments passed to the application are basic strings or numbers, and sometimes data types such as List need to be passed
    • The List and Set:
      • There are two ways for SpringBoot to fill automaticallyListProperties:
        • Write as an array in the application.properties file
        spring.logger.smtpServers[0]=server1
        spring.logger.smtpServers[1]=server1
        Copy the code
        • Yml itself supports the List type, which can be added in the application.yml file
        spring:
        	mail:
        		smtpServers:
        			- server1
        			- server2
        Copy the code
      • The set collection is configured in the same way
    • You are advised to use YML for data configuration, which is easier to read and hierarchical
  • Duration:
    • SpringBoot has built-in support for resolving duration from configuration parameters:
    @Data
    @ConfigurationProperties(prefix = "spring.logger")
    class loggerModuleProperties {
    	private Duration pauseBetweenLogs;
    }
    Copy the code
    • You can configure either a millisecond value or text with units:
    spring.logger.pause-between-logs=5s
    Copy the code
    • If duration does not have a write unit, it is specified in milliseconds by default. You can also specify the unit by @durationUnit:
    @Data
    @ConfigurationProperties(prefix = "spring.logger")
    class loggerModuleProperties {
    	@DurationUnit(ChronoUnit.SECONDS)
    	private Duration pauseBetweenLogs;
    }
    Copy the code
    • 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 usage, the default unit is byte, which can be specified by the @datasizeUnit
    @Data
    @ConfigurationProperties(prefix = "spring.logger")
    class loggerMailModuleProperties {
    	@DataSizeUnit(DataUnit.MEGABYTES)
    	private DataSize maxAttachmentSize = DataSize.ofMegebytes(2);
    } 
    Copy the code
    • Add configuration:
    spring.logger.max-attachment-size=1MB
    Copy the code

    The output results are as followsB(bytes)Is displayed in units

    • Common units are as follows:
      • B: BYTES
      • KB: KILOBYTES
      • MB: MEGEBYTES
      • GB: GIGABYTES
      • TB: TERABYTES
  • Custom types:
    • Sometimes, you want to resolve configuration parameters to custom object types, such as custom item weights:
    spring.logger.max-attachment-weight=5kg
    Copy the code
    • Add the Weight attribute to MailModuleProeprties:
    @Data
    @ConfigurationProperties(prefix = "spring.logger")
    class MailModuleProperties {
    	private Weight maxAttachmentWeight;
    }
    Copy the code
    • Create a custom converter converter:
    class WeightConverter implements Convert<String.Object> {
    	@Override
    	public Weight convert(String source) {
    		// Create and return an object of Weight based on the source String}}Copy the code
    • Register the custom converter Converter into the SpringBoot context
    @Configuration
    class PropertiesConfig {
    	@Bean
    	@ConfigurationPropertiesBinding
    	public WeightConverter weightConverter(a) {
    		return newWeightConverter(); }}Copy the code

    @ConfigurationPropertiesBindingAnnotations are to letSpringBootUse this converter for data binding

  • The tag configuration attribute is Deprecated:
@DeprecatedConfigurationProperty(reason = "change name", replacement = "none")
public String getDefaultSubject(a) {
	return defaultSubject;
}
Copy the code

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 SpEL expressions, you can only select the @Value annotation

@Repository

  • Used to annotate data access components, known as 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, @ModelAttribute,And it applies to all of them@RequestMappingIn the
    • InitBinder: Initializes the data binder before execution
    • @modelAttribute: Get the value by binding it to the Model
    • @ExceptionHandler: Global exception capture processing

@Component

  • Referring to the component
  • You can use this annotation to annotate components when they cannot be categorized

@ResponseBody

  • Indicates that the result returned by the method is written directlyhttp response bodyIn the
    • Typically used when retrieving data asynchronously
  • After using @requestMapping, the return value is usually resolved to a jump path
  • Such as:
    • The result returned by @responseBody is not parsed as a jump path, but is written directly to the HTTP ResponseBody
    • Get json data asynchronously, add @responseBody, return JSON data directly

@RequestBody

  • Parameter is preceded by this annotation to indicate that the parameter is mandatory
  • Accepts a JSON string as a List of objects

@ComponentScan

  • The component scanning
  • Classes with @Component, @cotroller, @service, etc. annotations are scanned and registered as beans *

@Configuration

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

@ConditionOnProperty

  • Control Configuration takes effect when the condition is established
  • Properties:
    • Value: array, obtain the name of the corresponding property, and cannot be used together with name
    • Prefix: Indicates the prefix of the property name, which is optional
    • Name: the full or partial name of the array property (combined with prefix to form the full property name). It cannot be used together with value
    • HavingValue: Can be used in combination with name to compare whether the obtained attribute value and the given value of havingValue are the same
    • MatchMissing: Whether this property can be loaded without it. If true, the property will load normally without it. If false, an error is reported in the absence of the property, which is false by default
    • RelaxedNames: Whether loose matching is supported

@Bean

  • It’s the equivalent of XML, where the annotation is on the method
  • Represents generating a bean and handing it over to Spring to manage

@EnableAutoConfiguration

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

@Autowired

  • ByType way
  • Using the configured Bean, complete the assembly of properties and methods
  • Class members, methods, and constructors can be annotated for auto-assembly
  • If you add @autoWired (Required = false), no error is reported when the bean is not found

@Qualifier

  • When there are multiple beans of the same type, you can specify it using @qualifier (“name”)
  • Need to be used with @autowired

@Resource

  • @Resource(name = “name”, type = “type”)
  • If there are no attributes, the default is byName, similar to the @autoWired function

@RequestMapping

  • RequestMapping @requestMapping is an annotation to handle request address mapping, which can be used on a class or method
  • When used on a class, this address is used as the parent path for all methods in the class that respond to requests
  • RequestMapping has six attributes:
    • Params: Specifies that the request must contain certain parameter values for the method to process the request
    • Headers: Specifies that the request must contain some specified header value before the method can process the request
    • Value: specifies the actual address of the request. The specified address can be the URI Template pattern
    • Method: Specifies the method type of the request, such as GET, POST, PUT, and DELETE
    • Consumes: Specifies the Type of the Content that is submitted to handle the requests. – Content-type. Such as: application, json, text, HTML
    • Produces: Specifies the content type returned, only if the specified type is in the (Accept) type in the Request header

@GetMapping

  • @getMapping, @postMapping is a composite annotation
  • @requestMapping (value = “/”, method = requestmethod.get (Post, Put, Delete))

@RequestParam

  • Used in front of method arguments
  • Equivalent to the request. The getParameter

@PathVariable

  • RequestMapping(“user/get/ MAC /{macAddress}”)
public String getByMacAddress(@PathVariable("macAddress") String macAddress) {}
Copy the code

If the parameter is the same as the name in the braces, the parentheses can be left blank after the comment

Global exception handling

@ControllerAdvice

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

@ExceptionHandler

  • @Exceptionhandler(Exception.class)
    • When applied to a method, the method is executed when the exception is encountered

SpringCloud

@EnableEurekaServer

  • Used on the SpringBoot boot class
  • Indicates that this is a Eureka service registry

@EnableDiscoveryClient

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

@LoadBalanced

  • Enable the load balancing capability

@EnableCircuitBreaker

  • Used on the SpringBoot boot class
  • Enabling the circuit breaker Function

HystrixCommand

  • @HystrixCommand(fallbackMethod = “backMethod”)
  • Used in a method, fallbackMethod specifies the circuit breaker callback method

@EnableConfigServer

  • Used on the SpringBoot boot class
  • Indicates that this is a configuration center. Enable Config Server

@EnableZuulProxy

  • Used on the SpringBoot boot class
  • Indicates that zuul routing is enabled

@SpringCloudApplication

  • A collection of microservice annotations containing:
    • @ SpringBootApplication: SpringBoot annotation
    • EnableDiscoveryClient: Register service center Eureka annotation
    • EnableCircuitBreaker: Breaker note
  • This is a note that every microservice must have