SpringBoot foundation and use

summary

introduce

  SpringBoot is a Java Web engineering framework based on spring, which can be understood as an upgrade of spring MVC. Spring MVC development projects usually have very cumbersome configurations. Spring boot provides default values for most commonly used configurations and provides a unified modification entry for developers.

HelloWorld

  the following will introduce the basic construction of the SpringBoot project with a simple project (HelloWorld).

Create project

1.establish Maven engineering
    (1).Click in turn File -> New -> Project -> Maven,Do not select template(Uncheck Create from archetype)
    (2).Set project name(HelloWorld),Workspace, etc
    (3).Set project coordinates and version
2.modify pom.xml(modify JDK Version, remove unnecessary parts, add plug-ins, etc)
3.Add necessary folders(src/main and src/test Medium java Folders and resources folder)
4.establish com.xxx.dao package
5.establish com.xxx.entity package
6.establish com.xxx.service package
7.establish com.xxx.controller package

  engineering structure:

HelloWorld
    |---src
        |---main
            |---java
                |---com.xxx
                    |---controller
                    |---service
                    |---dao
                    |---entity
                    |---App.java
            |---resources
        |---test
    |---pom.xml

Add dao layer method

  add classes and methods in com.xxx.dao:

package com.oner.dao;
public class DaoTest {
    public static String test() {
        return "DAO TEST.";
    }
}

Add service layer method

  add classes and methods in com.xxx.service:

package com.oner.service;
public class ServiceTest {
    public static String test() {
        /* Call DAO layer method */
        return DaoTest.test() + "\n\r" + "SERVICE TEST.";
    }
}

Add SpringBoot dependency

  add SpringBoot parent declaration in pom.xml:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project ... >
    ...
    <!-- SpringBoot The parent project declaration is used to inherit all dependencies in the project to the child project -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
    </parent>
    
    <groupId>com.oner</groupId>
    <artifactId>HelloWorld</artifactId>
    <version>1.0-SNAPSHOT</version>
    
    <dependencies>
        <!-- SpringBoot-Web Scenario dependency -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    
    <build>
    </build>
</project>

Add controller layer method

  create a new package and add classes and methods in the controller module:

package com.oner.controller;
/* @RestController It is the combination of @ Controller and @ ResponseBody */
@RestController
public class TestController {
    /* @GetMapping Annotation is the path mapping of GET method in RESTful */
    @GetMapping(value = "test")
    public String test() {
        /* Call Service layer method */
        return ServiceTest.test();
    }
}

Add startup class

  in the SpringBoot project, you need to use a startup class to start the whole project:

/* @SpringBootApplication Annotations are used to identify startup classes */
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        /* Incoming startup class */
        SpringApplication.run(App.class);
    }
}

   SpringBoot comes with a Tomcat server. Run the main method in the startup class to start the server.

Project deployment

  SpringBoot supports generating executable jar files to run the server directly. Add a plug-in in pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project ... >
    ...
    <!-- SpringBoot The parent project declaration is used to inherit all dependencies in the project to the child project -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
    </parent>
    
    <groupId>com.oner</groupId>
    <artifactId>HelloWorld</artifactId>
    <!-- Modify packaging format to jar -->
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    
    <dependencies>
        <!-- SpringBoot-Web Scenario dependency -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <!-- Used in project deployment Maven Plug in to package the project as executable jar file -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

  run the controller module using the Maven command:

/* Clean up, compile, and package projects */
clean compile package

  find the generated target jar package and execute it with Java commands. The project is deployed.

java -jar controller.jar

Server access

   the default server port number of SpringBoot is "8080", and the default access path is "/




Core configuration

configuration file

file format

   SpringBoot supports files in both properties and yml formats, for example:

# Server port number
server.port=8080
# Request path
server.servlet.context-path=/oner

   yml is a configuration file that determines the hierarchical relationship by line beginning interval:

server:
    # The line beginning must be aligned between the same level
    port: 8080
    servlet:
        # The more indented level at the beginning of the line is the child level of the previous line
        context-path: /oner

Default profile

  the default configuration file name of SpringBoot is application.properties or application.yml. The default location of the SpringBoot configuration file is in the src/main/resources directory. All project parameters and settings are configured through this configuration file.

HelloWorld
    |---src
        |---main
            |---java
            |---resources
                |---application.yml(application.properties)
                |---static
                |---public
                    |---index.xml
        |---test
    |---pom.xml

  the idea of SpringBoot is that conventions are greater than configurations. Following this idea can quickly build stable and reliable projects. SpringBoot also supports the custom configuration file name and location, but it is not recommended. Such an operation is meaningless and breaks the idea that the Convention is greater than the configuration.

Server parameters

Default parameters

   SpringBoot comes with a Tomcat server. The default parameters are:

Port number:8080
 Access path:/(That is, if the access path is empty, you can directly"http://ip:port / "(add the request path after it)

Custom parameters

  properties method:

# Server port number
server.port=8080
# Request path
server.servlet.context-path=/oner

  yml mode:

server:
  # The line beginning must be aligned between the same level
  port: 8080
  servlet:
    # The more indented level at the beginning of the line is the child level of the previous line
    context-path: /oner

Static resources

  SpringBoot provides a default path for static resources:

HelloWorld
    |---src
        |---main
            |---java
            |---resources
                |---static
                |---public
                    |---index.xml
        |---test
    |---pom.xml

   common static resource paths are static and public. Static resources placed in these paths can directly reference the relative path of resources (relative to static,public...). For example, static/js/script.js can be directly referenced as js/script.js
   traditional Java Web projects need to place static resources in webapp. SpringBoot places static resources in the default path of static resources (commonly used, such as static,public...), places index.html in static, and the access site name automatically jumps to index.html

Interceptor

   after spring MVC defines the interceptor, it needs to register the interceptor with the configuration file, and SpringBoot uses the configuration class to register the interceptor.

Define interceptor

/* Defines a class that implements the HandlerInterceptor interface */
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        if(request.getSession().getAttribute("user") == null) {
            /* User is not logged in, request redirection to login page */
            response.sendRedirect(request.getContextPath() + "/login");
            /* Intercept request */
            return false;
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle() is executed.");
    }
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                @Nullable Exception exception) throws Exception {
        System.out.println("afterCompletion() is executed.");
    }
}

Define configuration class

The WebMvcConfigurer interface is used to configure spring MVC related parameters and settings.

/* The Configuration class must be declared with the @ Configuration annotation */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    /* addInterceptors()Method is used to register interceptors */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String includes = {"/users","/balance"};
        String excludes = {"/users/icon"};
        
        /* Register the interceptor and pass in the interceptor object;
           addInterceptor(HandlerInterceptor interceptor)Method to pass in the interceptor object and register the interceptor
           addPathPatterns(String ... patterns)Method to specify the included interception path;
           excludePathPatterns(String ... patterns)Method to specify the excluded interception path;
           When the interception path and exclusion path are not added, all resource requests are intercepted by default;
           If "/ * *" is passed in, all resource requests will be intercepted */
        registry.addInterceptor(new UserInterceptor())
            .addPathPatterns(includes).excludePathPatterns(excludes);
    }
}

Character encoding

   the default encoding method of SpringBoot request and response is UTF-8. It also supports modification using configuration files. Use properties:

application.properties

# Enforce configured encoding
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true

  use yml:

application.yml

spring:
  http:
    encoding:
      # Enforce configured encoding
      force: true
      charset: UTF-8
      enabled: true




MyBatis integration

Environment construction

Add dependency

<!-- SpringBoot-MyBatis Integration scenario dependency -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>

<!-- MySQL Database driven dependency -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<!-- Alibaba Druid Database connection pool dependency -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.4</version>
</dependency>

Environment configuration

  add the following to the SpringBoot configuration file:

application.yml

spring:
  datasource:
    # Database connection pool
    type: com.alibaba.druid.pool.DruidDataSource
    # user name
    username: root
    # password
    password: 123456
    # Database connection URL
    url: jdbc:mysql://localhost:3306 / (omitted)
    # Database driven
    driver-class-name: com.mysql.cj.jdbc.Driver
        
mybatis:
  # Type aliases package is used to simplify references to entity Classpaths in SQL mapping files
  # After specifying the package name of the entity class, the SQL mapping file can directly reference the entity class name as the entity class path
  type-aliases-package: com.xxx.entity
  # SQL mapping file path (put it in the resources directory to create the mappers directory)
  mapper-locations: mappers/*.xml
  configuration:
    # Turn on the hump rule conversion of underlined in the database
    map-underscore-to-camel-case: true

   after SpringBoot integrates MyBatis, the global configuration of MyBatis is completed by the configuration file of SpringBoot, and there is no need to add an additional MyBatis global configuration file.

dao layer logic

Write entity

public class User {
    private Integer id;
    private String name;
    private String password;
    
    public User() {super();}
    public User(Integer id,String name,String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }
    
    public Integer getId() {return id;}
    public void setId(Integer id) {this.id = id;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public String getPassword() {return password;}
    public void setPassword(String password) {this.password = password;}
    
    @Override
    public String toString() {
        return "id:" + id + "," 
            + "name:" + name + "," 
            + "password:" + password + ".";
    }
}

Write dao

/* @Repository Annotations hand over dao instances to the Spring container for creation */
@Repository
/* @Mapper The annotation mark interface is an SQL mapping interface */
@Mapper
public interface UserDao {
    void addUser(@Param("user") User user);
    User getUserByName(@Param("name") String name);
}

    @ Mapper annotation is an empty annotation (no attribute) in MyBatis framework. Its function is to mark the interface as SQL mapping interface. It can play the same role by using @ MapperScan annotation on startup class:

/* SpringBoot Startup class */
@SpringBootApplication
/* Specify the package where the SQL mapping interface is located */
@MapperScan("com.xxx.dao")
public class App {
    public static void main(String[] args) {
        /* Incoming startup class */
        SpringApplication.run(App.class);
    }
}

SQL mapping

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- Namespace is the full class name of the query interface -->
<mapper namespace="com.oner.dao.UserDao">
    <!-- id Specify the query method name, and the reference to the entity class can refer to the class path -->
    <insert id="addUser" parameterType="com.oner.entity.User">
        <!-- "user"use@Param The specified parameter name is passed to the parameter using a placeholder SQL Statement, you can use"."operator -->
        insert into users(name,password) values (#{user.name},#{user.password})
    </insert>
    <!-- type-aliases-package After specifying the entity class package name, the reference to the entity class can directly reference the class name -->
    <select id="getUserByName" resultType="User">
        select * from users where name = #{name}
    </select>
</mapper>

service layer logic

Write service

/* @Service Annotations hand over instances of the service class to the Spring container for creation */
@Service
public class UserService {
    private UserDao userDao;
    public void addUser(User user) {
        userDao.addUser(user);
    }
    public User getUserByName(String name) {
        return userDao.getUserByName(name);
    }
}

Attribute injection

   after MyBatis is integrated with SpringBoot, the proxy object of the SQL mapping interface will be processed by SpringBoot as a Bean and placed in the Spring container without obtaining it through SqlSession. Therefore, the dao layer instance can be obtained by automatically assembling attribute injection in the service layer.

/* @Service Annotations hand over instances of the service class to the Spring container for creation */
@Service
public class UserService {
    
    /* Automatically assemble according to the type of the attribute, find the instance of the same type in the Spring container and assign the value to the attribute */
    @Autowired
    private UserDao userDao;
    
    public void addUser(User user) {
        /* Call injected properties */
        userDao.addUser(user);
    }
    public User getUserByName(String name) {
        /* Call injected properties */
        return userDao.getUserByName(name);
    }
}

    @ Autowired annotation is automatically assembled according to the type of attribute. Therefore, it cannot cope with the automatic assembly of multiple attributes whose type is to inherit the same class or implement the same interface. It can be used in conjunction with @ Qualifier annotation:

/* @Service Annotations hand over instances of the service class to the Spring container for creation */
@Service
public class UserService {
    
    /* Automatically assemble according to the type of the attribute, find the instance of the same type in the Spring container and assign the value to the attribute */
    @Autowired
    /* @Qualifier Automatically assemble according to the name of the Bean of the attribute type */
    @Qualifier(value = "userDao")
    private UserDao userDao;
    
    public void addUser(User user) {
        /* Call injected properties */
        userDao.addUser(user);
    }
    public User getUserByName(String name) {
        /* Call injected properties */
        return userDao.getUserByName(name);
    }
}

  @ Resource annotation is a combination of @ Autowired and @ Qualifier:

/* @Service Annotations hand over instances of the service class to the Spring container for creation */
@Service
public class UserService {
    
    /* @Resource Annotation is the combination of @ Autowired and @ Qualifier;
       Automatically assemble according to the attribute type and the Bean name corresponding to the type */
    /* Note that @ Resource is an annotation in the JDK. Use the name (not value) attribute to specify the name of the Bean */
    @Resource(name = "userDao",type = com.xxx.dao.UserDao.class)
    private UserDao userDao;
    
    public void addUser(User user) {
        /* Call injected properties */
        userDao.addUser(user);
    }
    public User getUserByName(String name) {
        /* Call injected properties */
        return userDao.getUserByName(name);
    }
}

controller layer logic

Write controller

/* @Controller The annotation leaves the instance of the controller class to the Spring container to create */
@Controller
public class UserController {
    
    private UserService userService;
    
    @ResponseBody
    public String test() {
        userService.addUser(new User(1,"Tony","123456"));
        return userService.getUserByName("Tony").toString();
    }
}

Attribute injection

/* @Controller The annotation leaves the instance of the controller class to the Spring container to create */
@Controller
public class UserController {
    
    /* Automatically assemble according to the type of the attribute, find the instance of the same type in the Spring container and assign the value to the attribute */
    @Autowired
    private UserService userService;
    
    @ResponseBody
    public String test() {
        /* Call injected properties */
        userService.addUser(new User(1,"Tony","123456"));
        /* Call injected properties */
        return userService.getUserByName("Tony").toString();
    }
}

Automatic injection mode

Common errors

The execution sequence of the Spring container is: first, call the constructor to create the Bean instance, then execute the attribute injection, so it will be wrong to call the injected attribute in the Bean constructor, because the Spring container has not executed the attribute injection at this time.

/* @Service Annotations hand over instances of the service class to the Spring container for creation */
@Service
public class UserService {
    
    /* Automatically assemble according to the type of the attribute, find the instance of the same type in the Spring container and assign the value to the attribute */
    @Autowired
    private UserDao userDao;
    
    public UserService() {
        /* Bean The creation of instances is before attribute injection, so it is wrong to call injected attributes in the constructor of Bean. */
        userDao.addUser(new User(1,"Tony","123456"));
    }
    
    public void addUser(User user) {
        /* Call injected properties */
        userDao.addUser(user);
    }
    public User getUserByName(String name) {
        /* Call injected properties */
        return userDao.getUserByName(name);
    }
}

Attribute injection

  @ Autowired or other annotations modify the attributes of a Bean, which is called attribute injection. Attribute injection is executed after the Bean instance is created.

/* @Service Annotations hand over instances of the service class to the Spring container for creation */
@Service
public class UserService {
    
    /* Attribute injection */
    @Autowired
    private UserDao userDao;
    
    public void addUser(User user) {
        /* Call injected properties */
        userDao.addUser(user);
    }
    public User getUserByName(String name) {
        /* Call injected properties */
        return userDao.getUserByName(name);
    }
}

Constructor Injection

  @ Autowired or other annotations modify the constructor of a Bean, which is called constructor injection. The Spring container will read the constructor parameter list and then automatically assemble the constructor parameters. Since attribute injection is executed after the constructor call, constructor injection can solve the problem of error in the injected attribute of the constructor call.

/* @Service Annotations hand over instances of the service class to the Spring container for creation */
@Service
public class UserService {
    
    private UserDao userDao;
    
    @Autowired
    public UserService(UserDao userDao) {
        this.userDao = userDao;
        userDao.addUser(new User(1,"Tony","123456"));
    }
    
    public void addUser(User user) {
        /* Call injected properties */
        userDao.addUser(user);
    }
    public User getUserByName(String name) {
        /* Call injected properties */
        return userDao.getUserByName(name);
    }
}

setter injection

   @ Autowired or other annotation modification of Bean methods is called setter injection. The Spring container will call the method and read the parameter list of the method, and then automatically assemble the parameters of the method. Setter injection is executed after the Bean instance is created.

/* @Service Annotations hand over instances of the service class to the Spring container for creation */
@Service
public class UserService {
    
    private UserDao userDao;
    
    /* setter Injection, @ Resource is the combination of @ Autowired and @ Qualifier */
    @Resource(name = "userDao",type = com.xxx.dao.UserDao.class)
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    
    public void addUser(User user) {
        /* Call injected properties */
        userDao.addUser(user);
    }
    public User getUserByName(String name) {
        /* Call injected properties */
        return userDao.getUserByName(name);
    }
}

Tags: Java Spring Spring Boot

Posted on Thu, 28 Oct 2021 05:51:31 -0400 by albinoazn