springBoot series --> springBoot annotations


1. List of annotations 

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

@Configuration is equivalent to Spring's XML configuration file; type safety can be checked using Java code.

@EnableAutoConfiguration  auto-configuration.

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

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

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

@Autowired is automatically imported.

@PathVariable gets parameters.

@JsonBackReference solves the problem of nested external links.

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

2. Detailed explanation of annotations

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

package com.mmzs.example.myproject;
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 acquiring 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 written directly into the HTTP response body.

For example, asynchronously obtaining json data and adding @responsebody will directly return json data. 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 the method usually needs to cooperate with the annotation @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");
     //The hello.html or hello.ftl template will be used for rendering and display.
     return"/hello";
  }
}

@RestController: It is used to mark control layer components (such as action in struts), a collection of @ResponseBody and @Controller, so that the obtained data will be automatically forwarded to json format when it is returned to the foreground. Sample code:

package com.kfit.demo.web;

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


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

  @Autowired
  private IUserService userService;   @RequestMapping("/test")   public String test(){
    Map<String, User> users = userService.queryAll();    return users;   } }

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

@EnableAutoConfiguration: Spring Boot auto-configuration: Attempts to auto-configure your Spring application based on the jar dependencies you add.

  For example, if HSQLDB exists on your classpath and you do not manually configure any database connection beans, then we will automatically configure an in-memory database". You can add the @EnableAutoConfiguration or @SpringBootApplication annotations to a @Configuration Classes to select auto-configuration. If you find that specific auto-configuration classes are applied that you do not want, you can use the exclude attribute of the @EnableAutoConfiguration annotation to disable them.

@ComponentScan: Indicates that the class will automatically discover and scan components.

  Personal understanding is equivalent to that if you scan classes with annotations such as @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 with the @Autowired annotation. All Spring components, including @Configuration classes, can be automatically collected. We often use the @ComponentScan annotation to search for beans and import them with the @Autowired annotation. 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 under the subpackage.

@Configuration: It is equivalent to a traditional xml configuration file. If some third-party libraries need to use xml files, 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.

@Component: refers to components in general. When components are not well classified, we can use this annotation to mark them.

@Service: components generally used to decorate the service layer

@Repository: Use the @Repository annotation to ensure that DAO or repositories provide abnormal translation. The DAO or repositories classes modified by this annotation will be discovered and configured by ComponentScan, and there is no need to provide XML configuration items for them.

@Bean: Equivalent to XML, it is placed above the method, not the class, which means that a bean (equivalent to the bean configured in XML) is generated and handed over to spring for management.

@Value: The value of the property that is injected into the Spring boot application.properties configuration. Sample code:

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

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

@AutoWired: Automatically import dependent beans. The default 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 the work of automatic assembly. When adding (required=false), no error will be reported even if the bean cannot be found.

@Qualifier: When there are multiple beans of the same type, @Qualifier("name") can be used to specify. When used with @Autowired, it is converted to byName (byName is identified by id) injection. The @Qualifier qualified descriptor can be injected according to the name, but it can control how to select candidates in a finer-grained manner. The specific usage is as follows:

@Autowired
@Qualifier(value = “demoInfoService”)
private DemoInfoService demoInfoService;
<bean id="userDao" class="..."/>  
<bean id="demoInfoService" class="...">  
    <property name="userDao">  
      <ref bean="userDao"/>  
    </property>  
</bean>  
<!-- Definition for student1 bean -->
<bean id="student1" class="com.tutorialspoint.Student">
     <property name="name"  value="Zara" />
     <property name="age"  value="11"/>
</bean>

<!-- Definition for student2 bean -->
<bean id="student2" class="com.tutorialspoint.Student">
     <property name="name"  value="Nuha" />
     <property name="age"  value="2"/>
</bean>

@Resource(name=”name”, type=”type”): If there is no content in parentheses, the default is byName (byName is identified by id). Similar thing to @Autowired.

3. JPA annotation

@Entity: @Table(name=""): Indicates that this is an entity class. Generally used for 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

@MappedSuperClass: Used on the entity that is determined to be the parent class. Attributes 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: Can be omitted if the field name is the same as the column name.

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

@Transient: Indicates that this property is not a mapping to a field of a database table, and the ORM framework will ignore this property. If an attribute is not a field mapping of a database table, it must be marked as @Transient, otherwise, the ORM framework defaults to its annotation as @Basic. @Basic(fetch=FetchType.LAZY): The tag can specify how entity properties are loaded

@JsonIgnore: The function is to ignore some properties in the Java bean during json serialization, and both 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 understanding

@RequestMapping: @RequestMapping("/path") indicates that this controller handles all URL requests for "/path". RequestMapping is an annotation for processing request address mapping, which can be used on classes or methods. 
Used on a class, indicating that all methods in the class that respond to requests use this address as the parent path. The annotation has six properties: 

params: Specifies that the request must contain certain parameter values ​​for this method to process.
headers: The specified request must contain certain specified header values ​​in order for this 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 submitted content type (Content -Type) of the processing request, such as application/json,text/ html;
produces: specifies the content type to be returned, which is only returned 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 curly braces .

5. Global exception handling

@ControllerAdvice: Contains @Component. can be scanned. Unified exception handling.

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

 


 

Reference article:

1. [springBoot series]--springBoot annotations

2. Spring @Qualifier annotation

1. List of annotations 

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

@Configuration is equivalent to Spring's XML configuration file; type safety can be checked using Java code.

@EnableAutoConfiguration  auto-configuration.

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

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

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

@Autowired is automatically imported.

@PathVariable gets parameters.

@JsonBackReference solves the problem of nested external links.

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

2. Detailed explanation of annotations

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

package com.mmzs.example.myproject;
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 acquiring 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 written directly into the HTTP response body.

For example, asynchronously obtaining json data and adding @responsebody will directly return json data. 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 the method usually needs to cooperate with the annotation @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");
     //The hello.html or hello.ftl template will be used for rendering and display.
     return"/hello";
  }
}

@RestController: It is used to mark control layer components (such as action in struts), a collection of @ResponseBody and @Controller, so that the obtained data will be automatically forwarded to json format when it is returned to the foreground. Sample code:

package com.kfit.demo.web;

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


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

  @Autowired
  private IUserService userService;   @RequestMapping("/test")   public String test(){
    Map<String, User> users = userService.queryAll();    return users;   } }

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

@EnableAutoConfiguration: Spring Boot auto-configuration: Attempts to auto-configure your Spring application based on the jar dependencies you add.

  For example, if HSQLDB exists on your classpath and you do not manually configure any database connection beans, then we will automatically configure an in-memory database". You can add the @EnableAutoConfiguration or @SpringBootApplication annotations to a @Configuration Classes to select auto-configuration. If you find that specific auto-configuration classes are applied that you do not want, you can use the exclude attribute of the @EnableAutoConfiguration annotation to disable them.

@ComponentScan: Indicates that the class will automatically discover and scan components.

  Personal understanding is equivalent to that if you scan classes with annotations such as @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 with the @Autowired annotation. All Spring components, including @Configuration classes, can be automatically collected. We often use the @ComponentScan annotation to search for beans and import them with the @Autowired annotation. 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 under the subpackage.

@Configuration: It is equivalent to a traditional xml configuration file. If some third-party libraries need to use xml files, 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.

@Component: refers to components in general. When components are not well classified, we can use this annotation to mark them.

@Service: components generally used to decorate the service layer

@Repository: Use the @Repository annotation to ensure that DAO or repositories provide abnormal translation. The DAO or repositories classes modified by this annotation will be discovered and configured by ComponentScan, and there is no need to provide XML configuration items for them.

@Bean: Equivalent to XML, it is placed above the method, not the class, which means that a bean (equivalent to the bean configured in XML) is generated and handed over to spring for management.

@Value: The value of the property that is injected into the Spring boot application.properties configuration. Sample code:

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

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

@AutoWired: Automatically import dependent beans. The default 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 the work of automatic assembly. When adding (required=false), no error will be reported even if the bean cannot be found.

@Qualifier: When there are multiple beans of the same type, @Qualifier("name") can be used to specify. When used with @Autowired, it is converted to byName (byName is identified by id) injection. The @Qualifier qualified descriptor can be injected according to the name, but it can control how to select candidates in a finer-grained manner. The specific usage is as follows:

@Autowired
@Qualifier(value = “demoInfoService”)
private DemoInfoService demoInfoService;
<bean id="userDao" class="..."/>  
<bean id="demoInfoService" class="...">  
    <property name="userDao">  
      <ref bean="userDao"/>  
    </property>  
</bean>  
<!-- Definition for student1 bean -->
<bean id="student1" class="com.tutorialspoint.Student">
     <property name="name"  value="Zara" />
     <property name="age"  value="11"/>
</bean>

<!-- Definition for student2 bean -->
<bean id="student2" class="com.tutorialspoint.Student">
     <property name="name"  value="Nuha" />
     <property name="age"  value="2"/>
</bean>

@Resource(name=”name”, type=”type”): If there is no content in parentheses, the default is byName (byName is identified by id). Similar thing to @Autowired.

3. JPA annotation

@Entity: @Table(name=""): Indicates that this is an entity class. Generally used for 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

@MappedSuperClass: Used on the entity that is determined to be the parent class. Attributes 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: Can be omitted if the field name is the same as the column name.

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

@Transient: Indicates that this property is not a mapping to a field of a database table, and the ORM framework will ignore this property. If an attribute is not a field mapping of a database table, it must be marked as @Transient, otherwise, the ORM framework defaults to its annotation as @Basic. @Basic(fetch=FetchType.LAZY): The tag can specify how entity properties are loaded

@JsonIgnore: The function is to ignore some properties in the Java bean during json serialization, and both 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 understanding

@RequestMapping: @RequestMapping("/path") indicates that this controller handles all URL requests for "/path". RequestMapping is an annotation for processing request address mapping, which can be used on classes or methods. 
Used on a class, indicating that all methods in the class that respond to requests use this address as the parent path. The annotation has six properties: 

params: Specifies that the request must contain certain parameter values ​​for this method to process.
headers: The specified request must contain certain specified header values ​​in order for this 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 submitted content type (Content -Type) of the processing request, such as application/json,text/ html;
produces: specifies the content type to be returned, which is only returned 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 curly braces .

5. Global exception handling

@ControllerAdvice: Contains @Component. can be scanned. Unified exception handling.

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

 


 

Reference article:

1. [springBoot series]--springBoot annotations

2. Spring @Qualifier annotation

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324673794&siteId=291194637