The most and most commonly used annotations in Spring Boot

1. List of annotations

@SpringBootApplication:  Contains @ComponentScan, @Configuration and @EnableAutoConfiguration annotations. Among them @ComponentScan lets spring Boot scan the Configuration class and add it to the program context.

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

@EnableAutoConfiguration  automatic configuration.

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

@Component  can be used with CommandLineRunner to perform some basic tasks after the program is started.

The @RestController  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 in the HTTP response body, which is a REST-style controller.

@Autowired is  automatically imported.

@PathVariable  gets the parameters.

@JsonBackReference  solves the problem of nested external links.

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

2. Detailed explanation of annotations

@SpringBootApplication:  Declare that spring boot will automatically configure the program as necessary. This configuration is equivalent to: @Configuration, @EnableAutoConfiguration and @ComponentScan three configurations.

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);
    }
}

@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. 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 directly written into the HTTP response body.

For example, to obtain 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”;
}

@Controller:  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 be annotated with @RequestMapping .

Sample code:

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

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

@RestController:  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";
    }
}

@RequestMapping:  Provide routing information, responsible for the mapping of URLs to specific functions in the Controller.

@EnableAutoConfiguration:  Spring Boot auto-configuration: Try to automatically configure your Spring application based on 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.

@ComponentScan:  Indicates that this class automatically discovers scanning components. Personal understanding is equivalent to scanning for classes annotated with @Component, @Controller, @Service, etc., and registering 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. We often use the @ComponentScan annotation to search for beans and import them in conjunction with the @Autowired annotation.

If there is no configuration, Spring Boot will scan the package where the startup class is located and the classes under the sub-packages with @Service, @Repository and other annotations.

@Configuration: It 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.

@Import:  used to import other configuration classes.

@ImportResource:  used to load the xml configuration file.

@Autowired:  automatically import dependent beans

@Service:  Generally used to decorate components of the service layer

@Repository:  Using the @Repository annotation can ensure that DAO or repositories provide exception translation. The DAO or repositories class modified by this annotation will be discovered and configured by ComponetScan, and there is no need to provide XML configuration items for them.

@Bean:  Annotating methods with @Bean is equivalent to beans configured in XML.

@Value:  Inject the value of the property configured in Spring boot application.properties.

Sample code:

@Value(value = “#{message}”)
private String message;

@Inject:  Equivalent to the default @Autowired, but there is no required attribute;

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

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

@AutoWired:  Automatically import 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.

@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;

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

Three, JPA annotation

@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 entity class name are the same, @Table can be omitted

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

@NoRepositoryBean:  Generally used as the repository of the parent class. With this annotation, Spring will not instantiate the repository.

@Column:  If the field name is the same as the column name, it can be omitted.

@Id:  Indicates that the attribute is the primary key.

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

@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, and the two names can be the same.

@Transient:  Indicates that this 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. @Basic(fetch=FetchType.LAZY): The tag can specify the loading method of entity attributes

@JsonIgnore: The  function is to ignore some properties in the Java bean when json serialization, serialization and deserialization are affected.

@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.

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

Four, springMVC related solutions

@RequestMapping:  @RequestMapping("/path") means that the controller processes all URL requests for "/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 type of content to be returned, and returns only when the (Accept) type in the request header contains the specified type

@RequestParam: Used  in front of method parameters.

@RequestParam String a =request.getParameter(“a”)。

@PathVariable:  Path variable. Such as

RequestMapping(“user/get/mac/{macAddress}”)
public String getByMacAddress(@PathVariable String macAddress){
    //do something;
}

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

Five, global exception handling

@ControllerAdvice:  Contains @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.

Guess you like

Origin blog.csdn.net/baidu_39322753/article/details/104657960