Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the notes commonly used in SpringBoot

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the notes commonly used in SpringBoot, which have a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

1. @ SpringBootApplication

This comment is the cornerstone of the SpringBoot project and will be added by default when creating the Application of the SpringBoot project.

@ SpringBootApplicationpublic class SpringSecurityApplication {public static void main (Strings [] args) {SpringApplication.run (SpringSecurityApplication,args);}}

@ SpringBootApplication is treated as a collection of @ Configuration,@EnableAutoConfiguration,@ComponentScan annotations

@ EnableAutoConfiguration: enable the automatic configuration mechanism of SpringBoot

@ ComponentScan: scan the bean annotated by @ Component / @ Service/@Controller. The annotation scans all classes under the package in which the class resides by default.

Configuration: allows you to register additional bean or import other configuration classes in the context of Spring

2. @ Bean

Registering Spring IOC containers with Bean objects and using bean objects is the focus of the entire Spring framework, where @ Bean is a way to register methods as Spring Bean objects.

Package com.edu.fruit; / / define an interface public interface Fruit {/ / No method} / * * define two subclasses * / package com.edu.fruit;@Configurationpublic class Apple implements Fruit {/ / constrain the Apple class to the Integer type} package com.edu.fruit;@Configurationpublic class GinSeng implements Fruit {/ / constrain the GinSeng class to the String type} / * * business logic class * / package com.edu.service;@Configurationpublic class FruitService {@ Autowired private Apple apple @ Autowired private GinSeng ginseng; / / defines a method to generate Bean @ 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 does this Bean come from, / / return an instance object of the Apple class from the method @ Bean above} three, @ Autowired

@ Autowired automatically injects annotations, the most commonly used annotation that automatically imports objects into classes and annotations classes that automatically assemble bean

4. Component family

@ Component: general annotations. You can use @ Component annotations when you don't know which layer Bean is on.

@ Repository: annotations corresponding to persistence layer-Dao layer, used to manipulate database related

@ Service: comments corresponding to the service layer, which are used 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 collection of @ Controller and @ ResponseBody annotations that are used to return the Json format to the page (the returned Json text with 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

Generally declare a configuration class, using @ Component or @ Configuration

@ Configurantionpublic class AppConfig {@ Bean public TransferService transferService () {return new TransferServiceImpl ();}} eight, @ RequsetMapping

@ RequsetMapping is the most common annotation for handling HTTP requests

@ RequestMapping ("/ users") public ResponseEntity getAllUsers () {return userRepository.findAll ();} VIII, @ GetMapping

Generally declare a configuration class, using @ Component or @ Configuration

9. @ Configuration

@ GetMapping is equivalent to @ RequestMapping (value= "/ users", method = RequsetMethod.GET)

Even using @ GetMapping is equivalent to using the receive GET method

@ GetMapping ("/ users") public ResponseEntity getAllUsers () {return userRepository.findAll ();} X, @ PostMapping

@ PostMapping is equivalent to @ RequestMapping (value= "/ users", method = RequsetMethod.POST)

Even using @ PostMapping is equivalent to using the receive Post method

@ PostMapping ("/ users") public ResponseEntity getAllUsers () {return userRepository.findAll ();} 11, @ PutMapping

@ PutMapping ("/ users/ {userId}") is equivalent to @ RequestMapping (value = "/ users/ {userId}", method = RequestMethod.PUT)

@ PutMapping ("/ users/ {userId}") public ResponseEntity updateUser (@ PathVariable (value = "userId") Long userId, @ Valid @ RequestBody UserUpdateRequest userUpdateRequest) {.} 12, @ 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) {.} XIII, @ ParhVariable and @ RequestParam

@ PathVariable is used to get path parameters, and @ RequestParam is used to obtain query parameters.

GetMapping ("/ users/ {userId} / teachers") public List 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, the value= "parameter name" required = "true/false" (true means the parameter is not allowed to exist, false means the parameter is not allowed to exist) defaultValue= "" sets the default required to false when setting defaultValue.

14. @ RequestBody

It is used to read the body part of the Request request, and the Content-Type is data in application/json format. After receiving the data, the data will be automatically bound to the Java object. The system will use HttpMessageConverter to convert the json string in the requested body into the Java object.

@ PostMapping ("/ sing-up") public ResponseEntity signUp (@ RequsetBody @ Valid UserRegisterRequest userRegisterRequest) {userService.save (userRegisterRequest); return ResponseEntity.ok () .build ()'}

This is a typical RequestBody to transfer data in a Post request. When the back-end Controller receives the data in json format, it will directly generate Java objects and map them to the UserRegisterRequest class, so that the userRegisterRequest objects can be stored directly. By the way, the @ Valid annotation uses the

To verify whether the data format meets the requirements. If it meets the requirements, it will pass. If it does not meet the requirements, prompt the message information in the notes.

Read configuration information

Read comments from application.yml

Wuhan2020: Wuhan, come on! Come on, China! My-profile: name: name email: XXXX@qq.comlibrary: location: dalian books:-name: name1 description: description1-name: name2 description: description2-name: name3 description: description3

1.@Value

Use @ Value ("${property}") to read simple configuration information

@ Value ("${wuhan2020}") String wuhan2020

2.@ConfigurationProperties

Read configuration information through @ ConfigurationProperties and bind to bean

@ Component@ConfigurationProperties (prefix = "library") class LibraryProperties {@ NotEmpty private String location; private List books; @ Data @ ToString static class Book {String name; String description;} 16, @ Qualifier

When there are multiple Bean of the same type, you can specify it with @ Qualifier ("name"). Used with @ Autowired. The @ Qualifier qualifier descriptor can be injected according to the name, but it has more fine-grained control over how to select candidates. The specific usage is as follows:

@ Autowired @ Qualifier (value = "demoInfoService") private DemoInfoService demoInfoService; 17, @ MapperScan

Spring-boot supports an annotation of the mybatis component that specifies the path of the mybatis interface class to complete the scanning of the mybatis interface.

It has the same effect as the @ mapper annotation, except that the scan entry is different. @ mapper needs to be added to each mapper interface class. So in most cases, the injection of the mapper interface is completed through the @ MapperScan annotation configuration path after the project directory is planned.

After adding the corresponding build dependency of mybatis. You can use this annotation.

Eighteen, @ CrossOrigin

@ CrossOrigin (origins = "", maxAge = 1000) this annotation is mainly intended to solve the problem of cross-domain access. This annotation can be enabled either across domains for the entire controller configuration or at the method level.

Nineteen, @ ControllerAdvice

@ ControllerAdvice and @ RestControllerAdvice: usually used with @ ExceptionHandler, @ InitBinder, @ ModelAttribute.

@ ControllerAdvice and @ ExceptionHandler work together to complete unified exception interception processing.

@ RestControllerAdvice is a collection of @ ControllerAdvice and @ ResponseBody, and you can return data in json format.

The following is the unified handling of data exception returns.

Comments on the introduction of resources

The @ ImportResource @ Import @ PropertySource annotations are all used to import custom configuration files.

@ ImportResource (locations= {}) imports other xml configuration files, requiring the standard to be on the main configuration class.

Import the configuration file @ PropertySource of property to specify the file path, which is equivalent to using the spring tag to complete the introduction of configuration items.

The @ import annotation is a common class that can be imported into a spring container for management.

21, @ Transactional

This annotation allows you to declare a transaction, which can be added to a class or method.

There is no need to configure transaction management separately in spring boot. In general, we will add transaction annotations to the servcie layer to start the transaction. Note that transactions can only be opened on the public method. And the rollback condition of the main transaction aspect. Normally, when we configure rollbackfor exception, if the method

The exception caught in will result in the invalidation of the transaction aspect configuration.

Thank you for reading this article carefully. I hope the article "what are the comments commonly used in SpringBoot" shared by the editor will be helpful to you. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report