Preface
Spring Boot Common Annotations
Tip: The following is the main body of this article. The following cases can be used as reference.
1. @SpringBootApplication
This note is the cornerstone of the Spring Boot project, which is added by default when creating the Application for the Spring Boot project
@SpringBootApplication public class SpringSecurityApplication{ public static void main(Strings[] args){ SpringApplication.run(SpringSecurityApplication,args); } }
@ SpringBootApplication as a collection of @Configuration, @EnableAutoConfiguration, @ComponentScan annotations
-
@EnableAutoConfiguration: Enable SpringBoot auto-configuration mechanism
-
@ComponentScan: scans bean s annotated by @Component /@Service/@Controller, which by default scans all classes under the package where the class resides
-
@Configuration: Allows additional bean s to be registered or other configuration classes to be imported in the Spring context
2. @Bean
Bean object registration Spring IOC containers and the use of bean objects are the focus of the entire Spring framework, where @Bean is one way to register methods as Spring Bean objects
package com.edu.fruit; //Define an interface public interface Fruit<T>{ //No way } /* *Define two subclasses */ package com.edu.fruit; @Configuration public class Apple implements Fruit<Integer>{//Constrain Apple class to Integer type } package com.edu.fruit; @Configuration public class GinSeng implements Fruit<String>{//Constrain GinSeng class to String type } /* *Business Logic Class */ package com.edu.service; @Configuration public class FruitService { @Autowired private Apple apple; @Autowired private GinSeng ginseng; //Define a method for generating beans @Bean(name="getApple") public Fruit<?> getApple(){ System.out.println(apple.getClass().getName().hashCode); System.out.println(ginseng.getClass().getName().hashCode); return new Apple(); } } /* *Test Class */ @RunWith(BlockJUnit4ClassRunner.class) public class Config { public Config(){ super("classpath:spring-fruit.xml"); } @Test public void test(){ super.getBean("getApple");//Where did this Bean come from? //An Apple class instance object was returned from the method below @Bean above } }
3. @Autowired
@ Autowired automatically injects annotations, the most common type of annotation automatically imports objects into classes, annotates classes that automatically assemble bean s
4. Component Family
@ Component: A generic annotation that can be labeled with the @Component annotation when you don't know on which level the Bean is.
@ Repository: Comment for the corresponding persistence layer - Dao layer, used to manipulate database dependencies
@ Service: Comment for the corresponding service layer to connect the Dao layer for logical processing
@ Controller: Corresponds to the Spring MVC control layer, which mainly receives user requests and calls service to return to the front-end page
5. @RestController
@ The RestController annotation is a combination of the @Controller annotation and the @ResponseBody annotation used to return the Json format to the page (the Json text returned is in Rest format)
6. @Scope
Declare the scope of Spring Bean
@Scope("singleton") public Person personSingleton(){ return new Person(); }
Four scopes of Spring Bean: singleton,prototype,request,session
7. @Configuration
General declaration of configuration class using @Component or @Configuration
@Configurantion public class AppConfig{ @Bean public TransferService transferService(){ return new TransferServiceImpl(); } }
8. @RequsetMapping
@ RequsetMapping is the most common comment for handling HTTP requests
@RequestMapping("/users") public ResponseEntity<List<User>> getAllUsers(){ return userRepository.findAll(); }
8. @GetMapping
General declaration of configuration class using @Component or @Configuration
9. @Configuration
@ GetMapping is equivalent to @RequestMapping (value='/users', method =RequsetMethod.GET)
Even with @GetMapping, the GET method is pretty useful
@GetMapping("/users") public ResponseEntity<List<User>> getAllUsers(){ return userRepository.findAll(); }
10. @PostMapping
@ PostMapping is equivalent to @RequestMapping (value='/users', method =RequsetMethod.POST)
Even using @PostMapping is quite a way to receive Posts
@PostMapping("/users") public ResponseEntity<List<User>> getAllUsers(){ return userRepository.findAll(); }
Eleven, @PutMapping
@ PutMapping ('/users/{userId}') is equivalent to @RequestMapping(value ='/users/{userId}', method = RequestMethod.PUT)
@PutMapping("/users/{userId}") public ResponseEntity<User> updateUser(@PathVariable (value ="userId")Long userId, @Valid @RequestBody UserUpdateRequest userUpdateRequest){ ... }
Twelve, @DeleteMapping
@ DeleteMapping ('/users/{userId}') is equivalent to @RequestMapping (value ='/users/{userId}', method = RequestMethod.DELETE)
@DeleteMapping("/users/{userId}") public ResponseEntity deleteUser(@PathVariable(value = "userId) Long userId){ ... }
Thirteen, @ParhVariable and@RequestParam
@ PathVariable is used to get path parameters and @RequestParam is used to get query parameters
@GetMapping("/users/{userId}/teachers") public List<Teacher> getUserRelatedTeachers(@PathVariable("userId") Long userId,@RequestParam(value = "type",required = false) String type){ ... }
Where @PathVariable is the {userId} value in the get request and @RequestParam is the type value in the url read request
For example, in our url request/users/{123456}/teachers?type=Chinese, what we get in Controller is userId=123456, type=Chinese
Also in @RequestParam, value = "parameter name" required = "true/false" (true means parameter does not allow to exist, false means parameter does not allow to exist) defaultValue= "" sets defaultValue with defaultrequired false.
14. @RequestBody
Used to read the body part of the Request request, with Content-Type data in application/json format, the data is automatically bound to the Java object upon receipt, and the JSON string in the requested body is converted to a Java object using HttpMessageConverter
@PostMapping("/sing-up") public ResponseEntity signUp(@RequsetBody @Valid UserRegisterRequest userRegisterRequest){ userService.save(userRegisterRequest); return ResponseEntity.ok().build()' }
This is the typical RequestBody that transfers data in a Post request. When the backend Controller receives data in json format, it directly generates a Java object that maps to the UserRegisterRequest class, allowing the userRegisterRequest object to be stored directly. By the way, the @Valid comment is used to verify that the data format meets the requirements, passes if it meets the requirements, does not meet the requirements, and prompts for message information in the comment
15. Read Configuration Information
Read the comment for application.yml
wuhan2020: Go to Wuhan! Go China! my-profile: name: name email: XXXX@qq.com library: location: dalian books: - name: name1 description: description1 - name: name2 description: description2 - name: name3 description: description3
1.@Value
Read simple configuration information using @Value("${property}")
@Value("${wuhan2020}") String wuhan2020;
2.@ConfigurationProperties
Read configuration information and bind to bean s through @Configuration Properties
@Component @ConfigurationProperties(prefix = "library") class LibraryProperties{ @NotEmpty private String location; private List<Book> books; @Data @ToString static class Book{ String name; String description; } }
Sixteen, @Qualifier
When you have multiple beans of the same type, you can specify them with @Qualifier("name"). Use with @Autowired. @ Qualifier qualified descriptors provide finer-grained control over how candidates are selected, in addition to being injected by name, as follows:
@Autowired @Qualifier(value = "demoInfoService") private DemoInfoService demoInfoService;
Seventeen, @MapperScan
spring-boot supports a comment on the mybatis component that specifies the path to the mybatis interface class to complete the scan of the mybatis interface.
It works the same way as the @mapper annotation, except that the scanning entries are different. @ The mapper needs to be added to each mapper interface class. So in most cases, the injection of the mapper interface is done through the @MapperScan annotation configuration path after the project catalog has been planned.
After adding mybatis corresponding build dependencies. You can use this comment.
Eighteen, @CrossOrigin
@ The annotation CrossOrigin(origins = ", maxAge = 1000) is intended to address cross-domain access issues. This annotation can be enabled across domains for the entire controller configuration or at the method level.
19. @ControllerAdvice
@ Controller Advice and @RestController Advice: Usually used with @ExceptionHandler, @InitBinder, @ModelAttribute.
@ Controller Advice and @ExceptionHandler work together to complete uniform exception interception processing.
@ RestControllerAdvice is a collection of @ControllerAdvice and @ResponseBody that can return data in json format for exceptions.
The following is the unified handling of data exception returns.
Notes on Resource Import
@ The three notes ImportResource @Import @PropertySource are used to import some custom configuration files.
@ ImportResource(locations={}) imports other xml configuration files, requiring standards on the primary configuration class.
Importing a property configuration file @PropertySource specifies the file path, which is equivalent to using the spring tag to complete the introduction of configuration items.
@ The import annotation is a management that imports generic classes into the spring container
21. @Transactional
This annotation allows you to declare transactions and add them to classes or methods.
Instead of configuring transaction management separately in spring boot, we typically add transaction annotations at the servcie layer to open the transaction. It is important to note that transactions can only be opened on the public method. And the rollback condition of the primary transaction facet. Normally when we configure rollbackfor exception s, if exceptions are caught in the method, the transaction facet configuration will fail.
summary
This article has sorted out the commonly used comments of Spring Boot, and will continue to update this article in the future. You are welcome to improve the comments and omissions.