Summary of the use of springboot framework

1. Introduction to SpringBoot

Spring Boot is a sub-project under the Spring open source organization, and its design purpose is to simplify the initial setup and development process of new Spring applications. The framework adopts the "convention is greater than configuration" approach and provides various starters to quickly build Spring applications.

Two, SpringBoot features

SpringBoot features

  • Easy to use, improve development efficiency, and provide a faster and more extensive introductory experience for Spring development.
  • Out of the box, away from cumbersome configuration.
  • Embedded Servlet container such as Tomcat or Jetty;
  • Provide automatic configuration of "starter" project object model (POMS) to simplify Maven configuration;
  • Provides a series of non-business functions common to large-scale projects, such as: embedded server, security management, operation data monitoring, operation status check and external configuration, etc.
  • There is no code generation, and no XML configuration is required.

What is out of the box?

Out of the box, Outofbox refers to the management of the life cycle of the object by adding relevant dependency packages to the pom file of the MAVEN project, and then using corresponding annotations instead of cumbersome XML configuration files. This feature allows developers to get rid of complex configuration work and dependent management work, and focus more on business logic.

What is convention over configuration?

Convention is better than configuration. Convention over configuration is a software design paradigm in which SpringBoot itself configures the target structure and developers add information to the structure. Although this feature reduces some flexibility and increases the complexity of BUG location, it reduces the number of decisions developers need to make, and at the same time reduces a lot of XML configuration, and can automate code compilation, testing, and packaging. .

Three, SpringBoot commonly used annotations

Initiate similar attention solutions

  • @SpringBootApplication: startup annotation, @SpringBootApplication is a composite annotation, including @ComponentScan, and @SpringBootConfiguration, @EnableAutoConfiguration

  • @SpringBootConfiguration inherits from @Configuration. The functions of the two are also the same. The current class is marked as a configuration class, and one or more instances of methods declared in the current class marked with @Bean annotations will be included in the srping container, and the instance name It is the method name.

  • The function of @EnableAutoConfiguration is to start automatic configuration. The @EnableAutoConfiguration annotation means that Springboot configures the default configuration of your project according to the jar package you add. For example, according to spring-boot-starter-web, you can determine whether your project needs to be added. webmvc and tomcat will automatically help you configure the default configuration required in the web project.

  • @ComponentScan, scans the classes marked by @Component, @Controller, @Service, and @Repository annotations under the current package and its sub-packages and incorporates them into the spring container for management. Equivalent to context: component-scan (the tag used by the spring framework in xml to scan for parallel support for package configuration).

  • @ServletComponentScan: After using the @ServletComponentScan annotation on SpringBootApplication, Servlet, Filter, and Listener can be directly registered automatically through the @WebServlet, @WebFilter, and @WebListener annotations without additional code.

  • @MapperScan(""): The @MapperScan annotation will only scan the interfaces in the specified package, not the classes.

  • @EnableScheduling: Spring's own timing service annotations, used on classes to start timing services, @Scheduled is used on methods, you can set the method timing time

Controller layer is concerned about the solution

  • @Controller: Used to respond to the page, indicating that the current class is a controller.
  • @RestController: It is a combination of @ResponseBody and @Controller, indicating that the current class is a controller and returns a set of data, not a page
  • @Autowired: Assemble dependent objects by type
  • @Resource: You can assemble objects by name or type
  • @RequestMapping: The role is URL mapping, used for the front-end interface to call specific methods in the Controller
  • @GetMapping: shorthand for @RequestMapping(method = RequestMethod.GET), used to process the GET type of the request method
  • @PostMapping: shorthand for @RequestMapping(method = RequestMethod.POST), used to process the POST type of the request method
  • @PutMapping: Shorthand for @RequestMapping(method = RequestMethod.PUT), which is equivalent to PostMapping and is used to submit information to the server. If it is to add information, I tend to use @PostMapping, and if it is to update information, I tend to use @PutMapping. The difference between the two is not very obvious.
  • @DeleteMapping: shorthand for @RequestMapping(method = RequestMethod.DELETE), used to process the DELETE type of the request method
  • @PathVariable: Through @PathVariable, the placeholder parameters in the URL can be bound to the input parameters of the controller processing method: the {xxx} placeholder in the URL can be bound to the operation method by @PathVariable("xxx") Into the ginseng.

Note: @Autowired annotation assembles dependent objects according to type (byType). By default, it requires dependent objects to exist. If null values ​​are allowed, you can set its required attribute to false. If we want to use byName to assemble, we can use it in conjunction with the @Qualifier annotation. as follows:

  @Autowired
  @Qualifier("person")
  private Person person; 

Resource is automatically injected according to ByName by default, provided by J2EE, and the package javax.annotation.Resource needs to be imported. @Resource has two important attributes: name and type, and Spring parses the name attribute annotated with @Resource as the name of the bean, and the type attribute parses as the type of the bean.

Therefore, if the name attribute is used, the automatic injection strategy of byName is used, and the automatic injection strategy of byType is used when the type attribute is used. If neither the name nor the type attribute is specified, then the byName automatic injection strategy will be used through the reflection mechanism.

	@Resource(name="person")
	private Person person; 

Service layer related solution

  • @service: used to annotate business layer components

Dao layer phase attention solution

  • @Repository: It can be marked on any class to indicate that the class is used to perform database-related operations (ie dao objects), and supports automatic handling of exceptions generated by database operations

Four, SpringBoot configuration

SpringBoot automatic configuration principle

SpringBoot automatic configuration is mainly done through several annotations such as @EnableAutoConfiguration, @Conditional, @EnableConfigurationProperties or @ConfigurationProperties.

When Spring Boot starts, the main configuration class is first loaded. @EnableAutoConfiguration turns on automatic configuration. The main function is to use EnableAutoConfigurationImportSelector to import some components into the container, and add all the values ​​of EnableAutoConfiguration configured in META-INF/spring.factories under the classpath to the container. in;

@Conditional conditional annotation, determine whether to load and automatically configure this class by judging whether there is a correspondingly configured jar package in the classpath.

The function of @EnableConfigurationProperties is to provide specific configuration parameters for automatic configuration, which only need to be written in application.properties, and then they can be written into the POJO properties of the configuration class through mapping.

Spring Boot configuration loading order

In Spring Boot, there are several ways to load configuration.

1) properties file;

2) YAML file;

3) System environment variables;

4) Command line parameters;

SpringBoot internal configuration file loading sequence

If there are multiple configuration files in different directories, their reading order is:
1. config/application.properties (under the config directory in the project root directory)
2. config/application.yml
3. application.properties (project root Directory)
4. application.yml
5. resources/config/application.properties (under the config directory in the resources directory of the project)
6. resources/config/application.yml
7. resources/application.properties (under the resources directory of the project)
8 , Resources/application.yml

Spring Boot handles cross-domain issues

What is cross-domain?

Cross-domain means that the browser cannot execute scripts of other websites. It is caused by the browser's same-origin policy and is a security restriction imposed by the browser on JavaScript.

Cross-domain in a narrow sense means that when any one of the protocol, domain name, and port of a request url is different from the current page url, it is cross-domain.

SpringBoot cross-domain solution

Option 1: Use @CrossOrigin annotation

Using @CrossOrigin annotation on the Controller, all interfaces under this class can be accessed through cross-domain, such as:

@CrossOrigin("www.baidu.com") // 只有指定域名可以访问该类下所有接口
public class CorsTestController {
    
    }

Solution 2: CORS global configuration-realize WebMvcConfigurer

New cross-domain configuration class:

/**
 * 跨域配置
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    
    

    @Bean
    public WebMvcConfigurer corsConfigurer()
    {
    
    
        return new WebMvcConfigurer() {
    
    
            @Override
            public void addCorsMappings(CorsRegistry registry) {
    
    
                registry.addMapping("/**").
                        allowedOrigins("www.baidu.com"). //允许跨域的域名,可以用*表示允许任何域名使用
                        allowedMethods("*"). //允许任何方法(post、get等)
                        allowedHeaders("*"). //允许任何请求头
                        allowCredentials(true). //带上cookie信息
                        exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果
            }
        };
    }
}

Solution 2: Customizing the interceptor implementation
To solve the cross-domain problem by implementing the Fiter interface and adding some headers to the request:

@Component
public class CorsFilter implements Filter {
    
    

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
    
    
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
    
    
            response.getWriter().println("ok");
            return;
        }
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
    
    
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    
    }
}

Guess you like

Origin blog.csdn.net/qq_37765808/article/details/114445545