These 5 commonly used SpringBoot annotations, no one knows?

1. Annotations list
1.
@SpringBootApplication contains @ComponentScan, @Configuration and @EnableAutoConfiguration annotations. Among them @ComponentScan lets Spring Boot scan the Configuration class and add it to the program context.

2. @ComponentScan
component scanning can automatically discover and assemble some beans.

3. @Configuration is
equivalent to Spring's XML configuration file; Java code can be used to check type safety.

4. @EnableAutoConfiguration
automatic configuration

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

6. @Autowired is
automatically imported.

7. @PathVariable
gets parameters.

8. @JsonBackReference
solves the problem of nested external links.

9. @RepositoryRestResourcepublic is used
with spring-boot-starter-data-rest.

Second, annotations (annotations) detailed explanation
1. @SpringBootApplication
declares that Spring Boot automatically configures the program as necessary. This configuration is equivalent to the three configurations of @Configuration, @EnableAutoConfiguration and @ComponentScan.
"2020 the latest Java basics and detailed video tutorials and learning routes!

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(Application.class, args);
    }
}
复制代码

2. @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 to build a RESTful api.

After using @RequestMapping, the return value is usually parsed as a jump path. After adding @ResponseBody, the return result will not be parsed as a jump path, but is directly written into the HTTP Response Body.

For example, after obtaining json data asynchronously, after adding @ResponseBody, the json data will be returned directly.

This annotation is generally used in conjunction with @RequestMapping.

Sample code:

@RequestMapping(/test”)
@ResponseBody
public String test(){
    
    
    return ”ok”;
}
复制代码

3. @Controller is
used to define the controller class. In the spring project, the controller is responsible for forwarding the URL request sent by the user to the corresponding service interface (service layer)

Generally, this annotation is in the class, and usually the method needs to cooperate with the annotation @RequestMapping.

Sample code:

@Controller
@RequestMapping(/demoInfo”)
publicclass DemoController {
    
    
    @Autowired
    private DemoInfoService demoInfoService;

    @RequestMapping("/hello")
    public String hello(Map map){
    
    
        System.out.println("DemoController.hello()");
        map.put("hello","from TemplateController.helloHtml");
        // 会使用hello.html或者hello.ftl模板进行渲染显示.
        return"/hello";
    }
}
复制代码

4. @RestController is
used to annotate control layer components (such as actions in struts), a collection of @ResponseBody and @Controller.

Sample code:

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(/demoInfo2”)
publicclass DemoController2 {
    
    

    @RequestMapping("/test")
    public String test(){
    
    
        return"ok";
    }
}
复制代码

5. @RequestMapping
provides routing information and is responsible for the mapping of URLs to specific functions in the Controller.

6. @EnableAutoConfiguration
Spring Boot auto-configuration (auto-configuration): Try to automatically configure your Spring application according to the jar dependencies you add.

For example, if HSQLDB exists on your classpath and you have not manually configured any database connection beans, then we will automatically configure an in-memory database".

You can add @EnableAutoConfiguration or @SpringBootApplication annotations to a @Configuration class to select automatic configuration.

If you find that specific auto-configuration classes you don't want are applied, you can disable them using the exclusion attribute of the @EnableAutoConfiguration annotation.

Search for the Java PhoenixMiles public account, reply to "back-end interview", and send you a copy of Java Interview Questions.pdf

7. @ComponentScan
means that this class will automatically discover scanning components.

Personal understanding is equivalent to that if you scan for classes annotated with @Component, @Controller, @Service, etc., and register them as Beans, you can automatically collect all Spring components, including @Configuration classes.

We often use the @ComponentScan annotation to search for beans and import them in conjunction with the @Autowired annotation. All Spring components can be collected automatically, including @Configuration classes.

If there is no configuration, Spring Boot will scan the classes annotated with @Service, @Repository, etc. under the package where the startup class is located and the subpackages.

8.
@Configuration is equivalent to the traditional xml configuration file. If some third-party libraries need to use the xml file, it is recommended to still use the @Configuration class as the main configuration class of the project-you can use the @ImportResource annotation to load the xml configuration file.

9. @Import is
used to import other configuration classes.

10. @ImportResource is
used to load the xml configuration file.

11. @Autowired
automatically imports dependent beans

12. @Service is
generally used to modify the components of the service layer

13.
@Repository uses @Repository annotation to ensure that DAO or repositories provide exception translation. DAO or repositories classes modified by this annotation will be discovered and configured by ComponetScan, and there is no need to provide XML configuration items for them.

14.
@Bean The @Bean annotation method is equivalent to the bean configured in XML.

15. @Value
injects the value of the property configured in Spring boot application.properties.

Sample code:

@Value(value = “#{
    
    message})
private String message;
复制代码

16. @Inject is
equivalent to the default @Autowired, but there is no required attribute;

17. @Component
refers to components in general. We can use this annotation to annotate when components are not easily classified.

18. @Bean is
equivalent to XML, placed above the method instead of the class, meaning that a bean is generated and managed by spring.

19. @AutoWired
automatically imports dependent beans. byType method. Use the configured Bean to complete the assembly of attributes and methods. It can annotate class member variables, methods, and constructors to complete automatic assembly. When (required=false) is added, no error will be reported even if the bean is not found.

20.
@Qualifier When there are multiple beans of the same type, you can use @Qualifier("name") to specify. Used in conjunction with @Autowired. The @Qualifier qualified descriptor can not only be injected according to the name, but can also be used for more fine-grained control over how to select candidates. The specific usage is as follows:

@Autowired
@Qualifier(value = “demoInfoService”)
private DemoInfoService demoInfoService;
复制代码

21. @Resource(name=”name”,type=”type”) If
there is no content in brackets, byName is the default. Do similar things with @Autowired.

Search for the Java PhoenixMiles public account, reply to "back-end interview", and send you a copy of Java Interview Questions.pdf

Three, JPA annotation
1, @Entity: @Table(name="")
indicates that this is an entity class. Generally used in jpa, these two annotations are generally used together, but if the table name and the entity class name are the same, @Table can be omitted.

2. @MappedSuperClass is
used to determine the entity that is the parent class. The properties of the parent class can be inherited by subclasses.

3. @NoRepositoryBean is
generally used as the repository of the parent class. With this annotation, Spring will not instantiate the repository.

4. @Column
can be omitted if the field name is the same as the column name.

5. @Id
indicates that the attribute is the primary key.

6. @GeneratedValue(strategy=GenerationType.SEQUENCE,generator= "repair_seq")
indicates that the primary key generation strategy is sequence (it can be Auto, IDENTITY, native, etc., Auto indicates that it can switch between multiple databases), and the name of the specified sequence is repair_seq .

7. @SequenceGeneretor(name = "repair_seq", sequenceName = "seq_repair", allocationSize = 1)
name is the name of the sequence for use. SequenceName is the sequence name of the database. The two names can be consistent.

8. @Transient
indicates that the attribute is not a mapping to a field of the database table, and the ORM framework will ignore this attribute.

If an attribute is not a field mapping of the database table, it must be marked as @Transient, otherwise, the ORM framework defaults its annotation as @Basic.

9. The @Basic(fetch=FetchType.LAZY)
tag can specify the loading method of entity attributes.

10. The
function of @JsonIgnore is to ignore some properties in the Java bean during json serialization, and both serialization and deserialization are affected.

11. @JoinColumn (name=”loginId”)
one-to-one: a foreign key in this table that points to another table. One-to-many: Another table points to the foreign key of this table.

12. @OneToOne, @OneToMany, @ManyToOne
correspond to one-to-one, one-to-many, and many-to-one in the hibernate configuration file.

Fourth, SpringMVC related solutions
1.
@RequestMapping @RequestMapping("/path") means that the controller handles all URL requests of "/path".

RequestMapping is an annotation used to process request address mapping, which can be used on classes or methods.

Used on classes, it means that all methods in the class that respond to requests use this address as the parent path. The annotation has six attributes:

params: Specifies that certain parameter values ​​must be included in the request before the method is processed.

headers: The specified request must contain certain specified header values ​​in order for the method to process the request.

value: Specify the actual address of the request, the specified address can be in URI Template mode

method: Specify the method type of the request, GET, POST, PUT, DELETE, etc.

consumes: Specify the content type (Content-Type) for processing the request, such as application/json, text/html;

produces: specifies the returned content type, and returns only when the (Accept) type in the request header contains the specified type.

2. @RequestParam is
used in front of the method parameters.

3. @PathVariable
path variable. Such as:

RequestMapping(“user/get/{
    
    macAddress})
public String getByMacAddress(@PathVariable String macAddress){
    
    
    //do something;
}
复制代码

The parameter must be the same as the name in the braces.

5. Global exception handling
@ControllerAdvice: includes @Component. Can be scanned. Handle exceptions uniformly.

@ExceptionHandler(Exception.class): Used on the method to indicate that the following method will be executed when this exception is encountered. .

Original link: https://juejin.cn/post/6907100256438059021

Guess you like

Origin blog.csdn.net/weixin_46699878/article/details/111401964