Dark Horse SpringBoot-Knowledge Gas Station

1.Idea shortcut keys

CTRL + F12: IDEA comes with the ability to view the attributes and methods of this class

CTRL+h: IDEA comes with viewing related implementation classes

2. Hide specified files or files of specified types in Idea

  1. Setting → File Types → Ignored Files and Folders
  2. Enter the file name to be hidden. The wildcard character * is supported.
  3. Press Enter to confirm adding

3. Copy the project

Note summary

  1. Copy the corresponding project in the workspace and modify the project name
  2. Delete the configuration files related to Idea and keep only the src directory and pom.xml file
  3. Modify the artifactId in the pom.xml file to be the same as the new project/module name
  4. remove name tag (optional)
  5. Keep a backup project for later use

in principle

  • Preserve engineering infrastructure
  • Erase the traces of the original project

Note: When modifying the pom file, you need to delete name and description, otherwise a maven index error will occur.

Insert image description here

That is, the order is wrong.

Insert image description here

4.REST style

4.1 Introduction to REST

Note summary

  1. REST
  2. Action 4
    • GET query
    • POST add/save
    • PUT increase
    • DELETE delete
  3. RESTful

REST (Representational State Transfer), representational state transfer

  • Traditional style resource description form

    http:/ / localhost/user/ getById?id=1

    http:/ / localhost/user/ saveUser

  • REST style description form

    http: / / localhost/user/1

    http: / / localhost/user

advantage:

  • Hide the access behavior of resources. It is impossible to know what operations are performed on the resources through the address.
  • writing simplification

The REST style simplifies the URL form of the address bar, which plays a certain role in security protection and makes it difficult to identify.

When accessing resources in REST style, use behavioral actions to distinguish what operations have been performed on the resources.

Insert image description here

Notice:

The above behavior is a convention, convention is not a specification and can be broken, so it is called REST style, not REST specification.
The name of the module description is usually plural, that is, the format description with s added, indicating this type of resource rather than a single resource, for example: users, books, accounts...

Accessing resources according to the REST style is called RESTful

4.2 RESTful entry case

Note summary

1. Getting Started Case
2. Request method setting
3. Request path parameters

1. Name:@RequestMapping

  • Type: method annotation

  • Location: Above the SpringMVC controller method definition

  • Function: Set the current controller method request access path

  • example:

    @RequestMapping(value = "/users", method = RequestMethod.POST)
    @ResponseBody
    public string save(@RequestBody User user){
          
          
        system.out.println( "user save. . ." + user);
        return "{ ' module' : 'user save' }";
    }
    
  • Attributes

    • value (default): request access path
    • method: http request action, standard action (GET/POST/PUT/DELETE)

2. Name: @PathVariable

  • Type: formal parameter annotation

  • Position: in front of the SpringMVC controller method parameter definition

  • Function: Bind the relationship between path parameters and processor method formal parameters, requiring one-to-one correspondence between path parameter names and formal parameter names

  • example:

    @RequestMapping(value = "/users/{id}" ,method = RequestMethod.DELETE)
    @ResponseBody
    public string delete(@PathVariable Integer id){
          
          
        system.out.print1n( "user delete. . ." + id);
        return "{ ' module ' : 'user delete' }" ;
    }
    

3.@RequestBody @RequestParam @PathVariable

  • the difference
    • @RequestParam is used to receive URL address parameters or form parameters.
    • @RequestBody is used to receive json data
    • @PathVariable is used to receive path parameters, use **{parameter name}** to describe the path parameters
  • application
    • In later development, when more than one request parameter is sent , the json format is the main one, and @RequestBody is widely used.
    • If sending data in non-json format, use @RequestParam to receive request parameters.
    • Use RESTful for development. When the number of parameters is small, such as 1 , you can use **@PathVariable** to receive the request path variable, which is usually used to pass the id value.
  1. Set http request action (verb)

    //增加
    @RequestMapping(value = "/users",method = RequestMethod.POST)
    @ResponseBody
    public String save(@RequestBody User user){
          
          
        System.out.println("user save..."+user);
        return "{'module':'user save...'}";
    }
    
    //修改
    @RequestMapping(value = "/users",method = RequestMethod.PUT)
    @ResponseBody
    public String update(@RequestBody User user){
          
          
        System.out.println("user update..."+user);
        return "{'module':'user update...'}";
    }
    
  2. Set request parameters (path variables)

    //删除
    @RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public String delete(@PathVariable Integer id){
          
          
        System.out.println("user delete...");
        return "{'module':'user delete...'}";
    }
    

    Keyword @PathVariable, be careful not to forget to add { id } characters to the path

Example:

//RESTful
@Controller
public class BookController {
    
    

    //增加
    @RequestMapping(value = "/users",method = RequestMethod.POST)
    @ResponseBody
    public String save(@RequestBody User user){
    
    
        System.out.println("user save...post");
        return "{'module':'user save...post'}";
    }

    //删除
    @RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public String delete(@PathVariable Integer id){
    
    
        System.out.println("user delete...");
        return "{'module':'user delete...'}";
    }

    //修改
    @RequestMapping(value = "/users",method = RequestMethod.PUT)
    @ResponseBody
    public String update(@RequestBody User user){
    
    
        System.out.println("user update..."+user);
        return "{'module':'user update...'}";
    }

    //查询--查询所有
    @RequestMapping(value ="/users",method = RequestMethod.GET)
    @ResponseBody
    public String getAll(){
    
    
        System.out.println("user getAll...");
        return "{'module':'user getAll...'}";
    }
    //查询--根据id查询
    @RequestMapping(value ="/users/{id}",method = RequestMethod.GET)
    @ResponseBody
    public String getById(@PathVariable Integer id){
    
    
        System.out.println("user getById..."+id);
        return "{'module':'user getById...'}";
    }

}


4.3REST rapid development

Note summary

1. RESTful rapid development (standard development)
2. @RestController
3. Standard request action mapping (4 types)

1. Name: @RestController

  • Type: class annotation

  • Position: Above the RESTful development controller class definition based on SpringMVC

  • Function: Set the current controller class to RESTful style, which is equivalent to the combined function of @Controller and @ResponseBody two annotations

  • example:

    @RestController
    public class BookController {
          
          
        
    }
    

2. Name: @GetMapping@PostMapping@PutMapping@DelgteMapping

  • Type: method annotation

  • Position: Above the RESTful development controller method definition based on SpringMVC

  • Function: Set the current controller method request access path and request action, each corresponding to a request action, for example, @GetNapping corresponds to GET request

  • example:

    @GetMapping("/{id}")
    public string getById(@PathVariable Integer id){
          
          
        system.out.println("book getById. . . "+id);
        return "{ ' module' : ' book getById ' }" ;
    }
    
  • Attribute
    value (default): Request access path

Example:

@RestController
@RequestMapping("/users")
public class BookController2 {
    
    

    //增加
    @PostMapping
    public String save(@RequestBody User user) {
    
    
        System.out.println("user save..." + user);
        return "{'module':'user save...'}";
    }

    //删除
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id) {
    
    
        System.out.println("user delete...");
        return "{'module':'user delete...'}";
    }

    //修改
    @PutMapping
    public String update(@RequestBody User user) {
    
    
        System.out.println("user update..." + user);
        return "{'module':'user update...'}";
    }

    //查询--查询所有
    @GetMapping
    public String getAll() {
    
    
        System.out.println("user getAll...");
        return "{'module':'user getAll...'}";
    }

    //查询--根据id查询
    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id) {
    
    
        System.out.println("user getById..." + id);
        return "{'module':'user getById...'}";
    }

}

5.Java Rest development model

Restful is a software architecture style and design style, not a standard. It only provides a set of design principles and constraints. Mainly used for client-server interactive software. Software designed based on this style can be simpler, more layered, and easier to implement caching mechanisms.

​ Restful style requests use "url+request method" to express the purpose of a request. The four verbs in the HTTP protocol indicating the operation mode are as follows:

  • Get: Get resources

  • Post: Create a new resource

  • Put: update resources

  • Delet: delete resources

Implement Rest mode through annotations:

@RestController: @ResponseBody + @Controller, which means the data returned is json format;

(The @RestController annotation is equivalent to the combination of @ResponseBody and @Controller)

@Controller
@ResponseBody
public class MyController {
     
      }

@RestController
public class MyRestController {
     
      }

  • @ResponseBody

    ​ 1. In actual operation, we only need to use the @RequestBody annotation in the Controller layer to deserialize the object;

    2. If you need to serialize the Controller's methods, we need to use @ResponseBody on the return value; you can also annotate @ResponseBody on the Controller class, so that all methods in this class can be serialized.

  • @Controller

    @Controller is a specialized @Component class. In actual operation, @Controller is used to indicate whether a Spring class can accept HTTP requests. It is usually bound to @ResponseBody.

  • @Component

    ​ 1. Instantiate ordinary POJO (Plain Ordinary Java Object simple java object) into the spring container, which is equivalent to the configuration file

    2. Generally refers to components. When components are difficult to classify, you can use the @Component annotation for annotation.

@GetMapping, @PostMapping, @DeletMapping, @PutMapping: correspond to four operation methods respectively.

Example:

//Rest模式
@RestController 
@RequestMapping("/books")
public class BookController {
    
    
 
    @GetMapping 
    public String getById() {
    
    
        System.out.println("springboot is running...");
        return "springboot is running...";
    }
 
    @DeletMapping("/{id}")
    public String getById() {
    
    
        System.out.println("springboot is running...");
        return "springboot is running...";
    }
 
}

Reference materials: A brief analysis of Java @RestController annotations_bit&y's blog-CSDN blog

6. Solution to automatic reminder function disappearing

Note summary

Specify SpringBoot configuration file

  1. Setting → Project Structure → Facets
  2. Select the corresponding project/project
  3. Customize Spring Boot
  4. Select profile

Insert image description here

Supplement: After idea2022 is thrown under resources, it will be automatically recognized. If it is not recognized, click Maven's refresh.

7.@Autowired annotation

What is it?

​ When the @Repository, @Component, and @Service annotations are used, spring's component scan will automatically discover it and initialize it as a bean in the spring application context .

When you need to use this bean, add the @Autowired annotation and the bean will be created.

Supplement: Initialization is based on the no-argument constructor.

what's the effect?

​The default is based on the attribute type, and spring automatically injects the matched attribute value.

how to use?

@Autowired annotation can be annotated on properties, methods and constructors

Recommendation: Annotate the constructor, as shown in the figure, mark the @Autowired annotation on the constructor.

Insert image description here

At this time, the initialization order of class members is different. The order is static members -> initialize variables to default values ​​-> constructor -> assign values ​​to variables.

If the annotation is on a property, the properties and methods of this property (object) cannot be used in the constructor.

Reference link: Detailed explanation of @Autowired annotations - super detailed and easy to understand_The Blog of Never Sleeping in Time-CSDN Blog_@autowired

8.@Repository、@Component、@Service、@Constroller注解

Their function is to hand over objects to spring management.

The role of the @Repository annotation is not only to identify the class as a Bean, but also to encapsulate the data access exceptions thrown in the annotated class into Spring's data access exception type. Spring itself provides a rich data access exception structure that is independent of specific data access technology, used to encapsulate exceptions thrown by different persistence layer frameworks, making exceptions independent of the underlying framework.

They are used at different levels of the software system:

  • @Component is a generalized concept that only represents a component (Bean) and can be used at any level.
  • @Service usually works at the business layer.
  • @Controller usually works at the control layer.
  • @Repository usually works in the persistence layer.

By using @Repository, @Component, @Service and @Constroller annotations on the class, Spring will automatically create the corresponding BeanDefinition object and register it in the ApplicationContext. These classes become Spring managed components. These three annotations act on classes at different software levels, and their usage is exactly the same as @Repository.

9.@Override annotation

  • Tell the reader that this method is overridden. Used to check whether the parent class method is correctly overridden.
  • The compiler can verify for you whether the method name under @Override is owned by your parent class, and if not, an error will be reported.

10.SSM

The SSM (Spring+SpringMVC+MyBatis) framework set is composed of two open source frameworks, Spring and MyBatis (SpringMVC is part of Spring). It is often used as a framework for web projects with relatively simple data sources.

11. How to write double colon in Java::

1. Expression: person -> person.getName(); can be replaced by: Person::getName

2. Expression: () -> new HashMap<>(); can be replaced by: HashMap::new

Insert image description here

12.The difference between put and post requests

In http, put is defined as an idempotent method, and post is not an idempotent method.

Idempotent: A term in mathematics. For a single input or no input operation method, if the result is the same every time, it is idempotent. In other words, if a network is executed multiple times and the effect is the same, it is idempotent.

  • post

    • Used to submit requests, can update or create resources, and is non-idempotent.

    • When a user registers, a user account is created for each submission. In this case, use post

  • put

    • Used to send updated resources to the specified URL, which is idempotent.

    • It is still a user module, such as changing a password. Although the account name and password are submitted, each submission only updates the user password, and each request only overwrites the value of the prototype. In this case, use put

Should I use post or put?

  • If the results of multiple calls to the URL corresponding to the update are consistent, use put
  • If you submit the same content every time and the final result is inconsistent, use post

Summarize

The request effect is generated: if the latter request overwrites the previous request, use put, and if the latter request superimposes the previous request, use post.

Reference materials: The difference between PUT and POST - Tencent Cloud Developer Community - Tencent Cloud (tencent.com)

Understand post and put in one minute (security and idempotent perspective)_"Logged out" blog-CSDN blog_Which one is safer, put or post?

13.What is the difference between @Component and @Bean?

  1. The objects of action are different: @Componentannotations act on classes, while @Beanannotations act on methods,
  2. @ComponentIt is usually automatically detected and automatically assembled into the Spring container through path scanning (we can use @ComponentScanannotations to define the path to be scanned to find out the classes that need to be assembled and automatically install them into the Spring bean container). @BeanAnnotations usually define the bean in the method marked with the annotation, @Beantelling Spring that this is an instance of a certain class, and return it to me when we need to use it.
  3. @BeanAnnotations @Componentare more customizable than annotations, and in many places we can only @Beanregister beans through annotations. For example, when we reference a class in a third-party library and need to assemble it into the Spring container, this can only be @Beanachieved through .

Reference link: What is the difference between Spring @bean and @component annotations? - Zhihu(zhihu.com)

[SpringBoot - Detailed explanation of the use of @Configuration and @Bean annotations (implementation of configuration class) (hangge.com)](https://www.hangge.com/blog/cache/detail_2506.html#:~:text=1, Instructions for use 1 %40Bean annotation acts on the method 2 %40Bean indicates that a method returns a Spring, 5 %40Bean annotation default scope is singleton scope, which can be set to prototype scope through %40Scope ("prototype"))

14.The difference between Controller and RestController

What they have in common: They are all used to indicate whether a certain Spring class can receive HTTP requests.

Differences: @Controller: identifies a Spring class as a Spring MVC controller processor, @RestController: @RestController is a combination of @Controller and @ResponseBody, the combined effect of the two annotations. Methods in the @Controller class can directly jump to jsp, ftl, html and other template pages by returning String. Adding the @ResponseBody annotation to the method can also return entity objects. All methods in the @RestController class can only return entity objects such as String, Object, and Json, and cannot jump to the template page.

Reference link: The difference between Controller and RestController_Linux Resource Station's blog-CSDN blog_The difference between controller and restcontroller

MockMvc

​ When performing integration testing on the module, we hope to test the Controller by entering the URL. If we start the server and establish an http client for testing, this will make the test very troublesome. For example, the startup speed is slow, the test verification is inconvenient, and the dependency Network environment, etc., so in order to test the Controller, we introduced MockMVC.

​ MockMvc implements the simulation of Http requests. It can directly use the network form and convert it to the call of the Controller. This can make the test fast and does not depend on the network environment. It also provides a set of verification tools, which can make the request verification Uniform and convenient.

Reference link: [Detailed explanation of MockMvc - Xingchao - Blog Park (cnblogs.com) My participation ] (https://www.cnblogs.com/jpfss/p/10950904.html#:~:text=MockMvc is solid, unified and very convenient.)

  • MockMvcRequestBuilders

15.The difference between @Component, @Repository and @Service

Reference links: The difference between @Component, @Repository, and @Service_fansili's blog-CSDN blog_@repository

annotation meaning
@Component The most common components can be injected into the spring container for management
@Repository Acts on persistence layer
@Service Acts on the business logic layer
@Controller Acts on the presentation layer (spring-mvc annotations)

16. Introduction to Druid

Druid is first and foremost a database connection pool. Druid is currently the best database connection pool, surpassing other database connection pools in terms of functionality, performance, and scalability, including DBCP, C3P0, BoneCP, Proxool, and JBoss DataSource. Druid has been deployed in more than 600 applications on Alibaba and has passed the rigorous test of large-scale deployment in production environments for more than a year. Druid is a database connection pool developed by Alibaba called for monitoring!

Reference links: What is Druid and an introduction to Druid_A java novice’s blog on his growth path-CSDN blog_What does druid do?

17. Data elimination strategy

Related configurations that affect data elimination

Detect volatile data (dataset server.db[i].expires that may expire)

  • volatile-lru: Select the least recently used data for elimination
  • volatile-lfu: select the least recently used data and eliminate it
  • volatile-ttl: select data that is about to expire and eliminate it
  • volatile-random: Randomly select data for elimination

Insert image description here

LFU: Select the least used data within a period of time for elimination.

LRU: Select the least recently used data within a period of time for elimination·

Guess you like

Origin blog.csdn.net/D_boj/article/details/129494827