Collation + understanding of Spring annotations

Annotations list

@SpringBootApplication

Action position:The @SpringBootApplication annotation is generally placed on a startup class of the project , which is used to inject the startup class into the container, to define the scope of container scanning, and to load some beans in the classpath environment.

@Target({
    
    ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {
    
    @Filter(
    type = FilterType.CUSTOM,
    classes = {
    
    TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {
    
    AutoConfigurationExcludeFilter.class}
)}
)

The core annotations of SpringBoot include @ComponentScan, @Configuration and @EnableAutoConfiguration annotations. Among them, @ComponentScan lets spring Boot scan to the Configuration class and add it to the program context.

@Configuration

Action position:@Configration annotation : Declare that the current class is a configuration class, which is equivalent to an XML file in Spring

Declare the current class as a configuration class , which is equivalent to the Spring configuration in xml form, and this annotation needs to be added to the class. It is equivalent to the XML configuration file of spring, replacing the xml file in spring by operating on the bean object.

@SpringBootConfiguration

This annotation is a derived annotation of @Configuration annotation,Consistent with the function of the @Configuration annotation, this class is marked as a configuration class , except that @SpringBootConfiguration is an annotation of springboot, while @Configuration is an annotation of spring

@EnableAutoConfiguration

**Position of action: **Generally used for startup classes,SpringBootApplication naturally integrates the @EnableAutoConfiguration annotation

@EnableAutoConfiguration Function: Turn on the automatic assembly function

Help the SpringBoot application to load all eligible @Configuration configurations into the current SpringBoot, create a Bean of the corresponding configuration class, and hand over the Bean entity to the IoC container for management.

@ComponentScan

**Function: **Component scanning

It can automatically discover and assemble some beans, annotate on the method or on the annotation, and scan the annotation of the package.

@Component

**Function: **Represented as a component

**Location:** Need to be registered to the public class in spring

You can use this annotation to describe the Bean in Spring, but it is a generalized concept, which only represents a component (Bean), and can be used at any level. When using it, you only need to mark the annotation on the corresponding class. (Instantiate the ordinary pojo into the spring container, which is equivalent to the one in the configuration file <bean id="" class=""/>)

@AutoConfigurationPackage

@AutoConfigurationPackage annotation, automatically injects all annotated classes (@Controller, @Service, etc.) and configuration classes (@Configuration) under the package under the main class

@ConfigurationPropertiesScan

Function: @ConfigurationPropertiesScan scans configuration properties, and the @EnableConfigurationProperties annotation is used to take effect for classes annotated with @ConfigurationProperties.

@EnableConfigurationProperties

**Function: **Make classes annotated with @ConfigurationProperties take effect.

If a configuration class only configures the @ConfigurationProperties annotation without using @Component, then the bean converted from the properties configuration file cannot be obtained in the IOC container. to be honest@EnableConfigurationProperties is equivalent to injecting all classes using @ConfigurationProperties at once.

@ConfigurationProperties

**Function: **spring-boot provides this annotation to map the value of the configuration file to the class.

When we use the application.properties/yml file to configure Thymeleaf, it is equivalent to operating the properties in the configuration file class corresponding to Thymeleaf.
When configuring , spring.thymeleaf.encoding=XXX时it is equivalent to assigning values ​​​​to the encoding properties in the following files. In the source code:
insert image description here

@AutoConfigureAfter

It is an annotation under the spring-boot-autoconfigure package,
**Function: **As the name implies, it is to load a configuration class after another configuration class.
For example:

@AutoConfigureAfter (AAAA.class)
public class CCCC {
    
    
}

Configuration CCCC will be loaded after AAAA

@AutoConfigureBefore

Likewise, the opposite of the above.

meta annotation

@Target({ElementType.TYPE})

Used to describe the usage scope of annotations (that is, where the described annotations can be used, such as in classes, methods, constructors, attributes, etc.), ElementType has the following parameter types:

Parameter Type Scope statement
TYPE Class, interface (including annotation types), or enumeration declarations
FIELD Field declarations (including enum constants)
METHOD Declared on the method using
PARAMETER parameter declaration
CONSTRUCTOR Use declared on constructor
LOCAL_VARIABLE Declare on local variables using
ANNOTATION_TYPE Use the declaration on the annotation
PACKAGE package declaration
TYPE_PARAMETER Annotations can be used in type parameter declarations (JDK1.8)
TYPE_USE Type Usage Declaration (JDK1.8)

@Retention

Indicates at what level the annotation information is saved, and is used to describe the life cycle of the annotation. (SOURCE<CLASS<RUNTIME)

Parameter Type illustrate
SOURCE Annotation information only exists during compiler processing, and there is no such Annotation information after compiler processing
CLASS The compiler stores Annotation in the .class file corresponding to the class. default behavior
RUNTIME The compiler stores Annotation in the class file and can be read by the JVM

@Document

Indicates whether the annotation is included in javadoc and whether to generate documentation comments. Annotation of classes and methods does not appear in javadoc by default. If the Annotation is decorated with @Documented, it means that it can appear in javadoc.

When defining Annotation, @Documented is optional; if not defined, Annotation will not appear in javadoc.

@Inherited

Indicates that subclasses can inherit the annotation in the parent class.

When using @interface to define an annotation, it means that it implements the java.lang.annotation.Annotation interface, that is, the annotation is an Annotation.

When defining Annotation, @interface is required.
Note: It is different from our usual implemented method. The implementation details of the Annotation interface are all done by the compiler. After defining an annotation through @interface, the annotation cannot inherit other annotations or interfaces.

Spring configuration related and injection of Bean object annotations

@Import

Used to import other configuration classes. Annotate on the class and introduce other configuration classes, similar to the ref in the bean tag

@ImportResource

Used to load xml configuration files.

@Bean

Annotate on the method, declare that the return value of the current method is a Bean object, which will be added to the Spring IOC container. Same as label. The instance name of the bean is specified by the parameter of the @Qualifier annotation. The name of this method is equivalent to the id attribute of the bean tag, and the return value is equivalent to the class attribute in the bean tag.

@Value

Inject the value of the property configured by Spring boot application.properties.

For example:

insert image description here

@Repository

**The role of @Repository:** This is because the role of this annotation is not only to identify the class as a Bean, but also to encapsulate the data access exception thrown in the marked class as Spring's data access exception type. Spring itself provides a rich and specific data access technology-independent data access exception structure, which is used to encapsulate exceptions thrown by different persistence layer frameworks, making exceptions independent of the underlying framework.

Using the @Repository annotation can ensure that DAO or repositories provide exception translation. The DAO or repositories classes decorated with this annotation will be discovered and configured by ComponentScan, and there is no need to provide XML configuration items for them. Its function is the same as @Component.

@Repository has similar functions to @Controller, @Service, and @Component, and they all hand over objects to spring management.

@Repository is used on the interface of the persistence layer. This annotation is to hand over an implementation class of the interface to spring management.

Why sometimes we don't use @Repository to annotate the interface, we can still inject into the implementation class of this interface?

1. The bean MapperScannerConfigurer is configured in the spring configuration file, which will scan the persistence layer interface to create an implementation class and hand it over to spring for management.

2. The @Mapper annotation is used on the interface or the @MapperScan annotation is used on the main class in springboot, which has the same function as MapperScannerConfigurer.

Note: If the @Repository annotation is not used, idea will report a warning that the bean cannot be found, just ignore it.

insert image description here

@Service

It usually acts on the business layer (Service layer), and is used to identify the class of the business layer as a bean in Spring, and its function is the same as @Component.

@Controller

It usually acts on the control layer (such as the Controller of Spring MVC), and is used to identify the class of the control layer as a bean in Spring, and its function is the same as @Component.

@RestController

This annotation is a collection of @Controller and @ResponseBody,Indicates that this is a controller bean, and the return value of the function is directly filled in the HTTP response body, which is a REST-style controller.

@JsonBackReference

Solve the problem of nested external links. Not commonly used, you can read this blog for details

@Scope

Setting the scope, marked on the class, is equivalent to the scope configuration in the bean in the configuration file.
<bean id="person" class="com.oldou.pojo.Person" scope="singleton"/>

Bean Object Dependency Injection Annotation

@Inject

Equivalent to the default @Autowired, but without the required attribute;

@Target({
    
    ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
    
    
    boolean required() default true;
}
@Target({
    
    ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Inject {
    
    
    boolean optional() default false;
}

@Autowired

Autowiring, by type byType. If it cannot be uniquely auto-assembled, then you need to pass @Qualifier(value="xxx")

@Qualifier

When there are multiple beans of the same type, they can be specified with @Qualifier("name"). Works with @Autowired. In addition to injecting by name, the @Qualifier qualified descriptor can perform more fine-grained control over how to select candidates. The specific usage is as follows:

@Autowired
@Qualifier(value = “demoInfoService”)
private DemoInfoService demoInfoService;

@Resource(name=”name”,type=”type”)

If there is no content in brackets, byName is the default. Do something similar to @Autowired (autowiring).

@Nullable

The field is marked with this annotation, indicating that the field is allowed to be null.

SpringMVC related notes

RequestMapping

@RequestMapping annotation is used to map url to controller class or a specific handler method.
Can be used on classes or methods. It is used on a class to indicate that all methods in the class that respond to requests use this address as the parent path.

Example: Specific to a certain page

insert image description here

@GetMapping

It is a shortcut of @RequestMapping(method =RequestMethod.GET) and can only handle Get type requests.

insert image description here

@PostMapping

It is a shortcut of @RequestMapping(method =RequestMethod.POST) and can only handle Post type requests.

insert image description here

@PutMapping

The @PutMapping annotation is short for @RequestMapping(method = RequestMethod.PUT).

@DeleteMapping

The @DeleteMapping annotation is short for @RequestMapping(method = RequestMethod.DELETE).

insert image description here

@RequestParam

Bind request parameters to controller method parameters.
Syntax:@RequestParam(value=”参数名”,required=”true/false”,defaultValue=””)

insert image description here

@ResponseBody

Indicates that the return result of this method is directly written into the HTTP response body, which is generally used when obtaining data asynchronously, and is used to build a RESTful API.

In RestController, we can see that ResponseBody is included in it. ResponseBody here is to make the data returned by the front desk a string in json format.

insert image description here

@RequestBody

It is used to receive the data in the json string passed from the front end to the back end (the data in the request body).
The @RequestBody annotation can convert data in JSON format into Java objects.
But it is required that the content-type is not the default application/x-www-form-urlcoded encoded content. Generally speaking, it is commonly used to deal with application/json types.
insert image description here

@PathVariable(“xxx”)

Get parameters. Through @PathVariable, the placeholder parameter {xxx} in the URL can be bound to the method parameter of the processor class @PathVariable("xxx"), for example:
@RequestMapping(value="user/{id}/{name} ")
Request path: http://localhost:8080/hello/show5/1/james

insert image description here

Guess you like

Origin blog.csdn.net/Ghoul___/article/details/126588372