Summary of common Spring Boot annotations

Summary of common Spring Boot annotations ...
1, Start annotation @ SpringBootApplication
2, Notes related to Controller
3, Get request parameter value
4, Injection bean correlation
5, Import profile
6, Transaction annotation @ Transactional
7, Global exception handling
Summary of common Spring Boot annotations

1, Start annotation @ SpringBootApplication

@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) }) public @interface SpringBootApplication { // ... omit the source code here }

Looking at the source code, we can find that @ SpringBootApplication is a composite annotation, including @ SpringBootConfiguration, @ EnableAutoConfiguration and @ ComponentScan

@The SpringBootConfiguration annotation inherits the @ Configuration annotation and is mainly used to load Configuration files

@SpringBootConfiguration inherits from @ Configuration and has the same functions. It indicates that the current class is a Configuration class, and will include one or more instances of methods declared in the current class marked with @ Bean annotation into the spring container, and the instance name is the method name.

@Enable autoconfiguration annotation to enable the autoconfiguration function

@EnableAutoConfiguration can help SpringBoot applications load all qualified @ Configuration configurations into the IoC container created and used by the current SpringBoot. With the support of Spring factoryesloader, an original tool class of the Spring framework, @ EnableAutoConfiguration can automatically configure intelligently, and the effect can be achieved

@ComponentScan annotation is mainly used for component scanning and automatic assembly

@The function of ComponentScan is to automatically scan and load qualified component or bean definitions, and finally load these bean definitions into the container. We can specify the automatic scanning range of @ ComponentScan through properties such as basePackages. If it is not specified, the default Spring framework implementation scans from the package of the class declaring @ ComponentScan. It is not specified by default, so the startup class of SpringBoot is best placed in the root package.

2, Notes related to Controller

@Controller

Controller to handle http requests.

@RestController composite annotation

View @ RestController source code

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Controller @ResponseBody public @interface RestController { /** * The value may indicate a suggestion for a logical component name, * to be turned into a Spring bean in case of an autodetected component. * @return the suggested component name, if any (or empty String otherwise) * @since 4.0.1 */ @AliasFor(annotation = Controller.class) String value() default ""; }

From the source code, we know that the @ RestController annotation is equivalent to the combination of @ ResponseBody+@Controller. The effect of RestController is to directly display the object returned by the method in json format on the browser

@RequestBody

Read the Request Body through the HttpMessageConverter and deserialize it into an Object (general reference) Object

@RequestMapping

@RequestMapping is one of the most commonly used annotations in Spring Web applications. This annotation maps HTTP requests to the processing methods of MVC and REST controllers

@GetMapping method annotation used to map HTTP get requests to specific handlers

Annotation abbreviation: @ RequestMapping(value = "/say",method = RequestMethod.GET) is equivalent to: @ GetMapping(value = "/say")

GetMapping source code

@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented @RequestMapping(method = RequestMethod.GET) public @interface GetMapping { //... }

It is the abbreviation of @ RequestMapping(method = RequestMethod.GET)

@PostMapping is a method annotation used to map HTTP post requests to specific handlers

@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented @RequestMapping(method = RequestMethod.POST) public @interface PostMapping { //... }

It is the abbreviation of @ RequestMapping(method = RequestMethod.POST)

3, Get request parameter value

@PathVariable: get data in url

@Controller @RequestMapping("/User") public class HelloWorldController { @RequestMapping("/getUser/") public String getUser(@PathVariable("uid")Integer id, Model model) { System.out.println("id:"+id); return "user"; } }

Request example: http://localhost:8080/User/getUser/123

@RequestParam: get the value of the request parameter

@Controller
@RequestMapping("/User")
public class HelloWorldController {

@RequestMapping("/getUser") public String getUser(@RequestParam("uid")Integer id, Model model) { System.out.println("id:"+id); return "user"; }

}

Request example: http://localhost:8080/User/getUser?uid=123

@The RequestHeader binds the value of the Request header part of the Request to the parameters of the method

@Cookie value binds the cookie value in the Request header to the parameter of the method

4, Injection bean correlation

@Repository

DAO layer annotation. The interface in DAO layer inherits jparepository < T, ID extends serializable >, and a jar related to jpa needs to be introduced into build.gradle for automatic loading.

Repository annotation source code

@Target() @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Repository { /** * The value may indicate a suggestion for a logical component name, * to be turned into a Spring bean in case of an autodetected component. * @return the suggested component name, if any (or empty String otherwise) */ @AliasFor(annotation = Component.class) String value() default ""; }

@Service

@Target() @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Service { /** * The value may indicate a suggestion for a logical component name, * to be turned into a Spring bean in case of an autodetected component. * @return the suggested component name, if any (or empty String otherwise) */ @AliasFor(annotation = Component.class) String value() default ""; }
  • @Service is a special case of @ Component annotation, which acts on classes
  • @The scope of Service annotation is singleton by default
  • When using annotation configuration and classpath scanning, the classes marked by @ Service annotation will be scanned by Spring and registered as beans
  • @Service is used to label service layer components, indicating that a bean is defined
  • @When using the Service, no parameters are passed. The Bean name defaults to the class name of the current class, with the first letter in lowercase
  • @Service("serviceBeanId") or @ Service(value = "serviceBeanId") use time passed parameters, and use value as the Bean name

@Scope scope annotation

@Scope acts on classes and methods, and is used to configure the scope of spring bean s. It identifies the scope of beans

@Scope source code

@Target() @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Scope { /** * Alias for {@link #scopeName}. * @see #scopeName */ @AliasFor("scopeName") String value() default ""; @AliasFor("value") String scopeName() default ""; ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT; }

Attribute introduction

value singleton Indicates that bean This is a single case.(default) prototype Indicates that bean Is multiple, that is, each use of the bean A new object is created when. request At once http One of the requests bean Corresponds to an instance. session In a httpSession One of them bean Corresponds to an instance. proxyMode DEFAULT Do not use proxy.(default) NO No proxy, equivalent to DEFAULT. INTERFACES Using an interface based proxy(jdk dynamic proxy). TARGET_CLASS Using class based proxies(cglib).

@Entity class annotation

@Table(name = "database table name"), this annotation is also annotated on the entity class, corresponding to the corresponding table in the database.
@The Id and @ Column annotations are used to label the fields in the entity class. The pk field is marked as @ Id and the rest @ Column.

@Bean method for generating a bean

@Bean explicitly indicates a method to generate a bean method, which is managed by the Spring container. Support alias @ bean ("XX name")

@Autowired auto import

  • @Autowired annotations work on constructors, methods, method parameters, class fields, and annotations
  • @Autowired annotation can realize the automatic injection of beans

@Component

Instantiating a normal pojo into the spring container is equivalent to the configuration file

Although @ Autowired is available, we still have to write a bunch of bean configuration files, which is quite troublesome. And @ Component tells spring that I am a pojo class. Register me in the container, and spring will automatically extract relevant information. Then we don't have to write a troublesome xml configuration file

5, Import profile

@PropertySource annotation

To import a single properties file:

@PropertySource(value = {"classpath : xxxx/xxx.properties"})

Introduce multiple properties files:

@PropertySource(value = {"classpath : xxxx/xxx.properties","classpath : xxxx.properties"})

@ImportResource import xml configuration file

It can be additionally divided into two modes: relative path classpath and absolute path (real path) file

Note: value or locations can not be written in a single file. Both value and locations are available

Relative path (classpath)

  • Import a single xml configuration file: @ importsource ("classpath: XXX / XXXX. XML")

  • Introduce multiple xml configuration files: @ importsource (locations = {"classpath: XXXX. xml", "classpath: yyyy. xml"})

Absolute path (file)

  • Import a single xml configuration file: @ importsource (locations = {"file: D: / hellxz / Dubbo. XML"})

  • Introduce multiple xml configuration files: @ importsource (locations = {"file: D: / hellxz / application. xml", "file: D: / hellxz / Dubbo. xml"})

Value: use the @ value annotation to get the value in the configuration file

@Value ("$ in properties")
private String xxx;

@Import imports additional configuration information

The function is similar to XML Configuration. It is used to import Configuration classes. You can import Configuration classes with @ Configuration annotation or implement ImportSelector/ImportBeanDefinitionRegistrar.

Use example

@SpringBootApplication @Import() public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }

6, Transaction annotation @ Transactional

In Spring, there are two ways to implement transactions: programmatic transaction management and declarative transaction management

  • Programming transaction management: programming transaction management uses TransactionTemplate or directly uses the underlying platform transactionmanager. For programmatic transaction management, spring recommends using the TransactionTemplate.
  • Declarative transaction management: Based on AOP. Its essence is to intercept before and after the method, and then create or join a transaction before the start of the target method. After the target method is executed, the transaction can be committed or rolled back according to the execution. The transaction operation can be carried out through @ Transactional, which is faster and simpler. Recommended use

7, Global exception handling

@ControllerAdvice handles exceptions uniformly

@The ControllerAdvice annotation defines the global exception handling class

@ControllerAdvice public class GlobalExceptionHandler { }

@The ExceptionHandler annotation declares exception handling methods

@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody String handleException(){ return "Exception Deal!"; } }

7 December 2021, 01:46 | Views: 7045

Add new comment

For adding a comment, please log in
or create account

0 comments