IDEA to quickly create a SpringBoot project

Posted by catlover on Tue, 08 Feb 2022 00:16:26 +0100

1 objectives

  • SpringBoot project can be created quickly (without writing any configuration files)
  • Introduction to the basic principles of SpringBoot
  • Introduction and use of SpringBoot configuration file
  • SpringBoot integrates Mybatis, Redis and timer
  • Spring boot sends Http request
  • Testing in SpringBoot
  • Spring boot packaged deployment

2 create a SpringBoot project using Spring Initializr

  • Configure item information

  • Check start dependency


The dependent Jar package is no longer handwritten by Pom file, but directly checked, which is much more convenient! After checking start dependency, you can create the project according to the normal steps.

So far, after the basic project is created, you only need to write the business code in the controller by yourself. There is no need to write pom files and the startup boot class of sprigboot. Compared with the previous project, the construction of the project is much simpler!

In addition, the annotations used to modify the boot class in the two projects are different. Obviously, the @ SpringBootApplication annotation is more convenient:

/*IDEA Quickly create a SpringBoot project*/

 * @SpringBootApplication One annotation is the top three:
 *  @Configuration Configuration class annotation, indicating that the current class is a configuration class
 *  @ComponentScan Package scanning annotation: if the parameter basePackages is not written, the current package and its sub packages will be scanned
 *  @EnableAutoConfiguration Turn on automatic configuration
public class Springboot02FasterApplication {

    public static void main(String[] args) {, args);

/*Maven Create a SpringBoot project*/

 * SpringBoot Boot class for
 * @Configuration Configuration class annotation, indicating that the current class is a configuration class
 * @ComponentScan Package scanning annotation: if the parameter basePackages is not written, the current package and its sub packages will be scanned
 * @EnableAutoConfiguration Turn on automatic configuration
public class DemoApplication {
    public static void main(String[] args) {
         * SpringBoot Application entry (standard configuration)
         * file of boot class, main function parameter)
         * The return value is the container of spring
        ConfigurableApplicationContext ioc =, args);

3 basic principles in springboot

3.1 starter

starters are the collation and encapsulation of dependencies and the integration of a set of dependent coordinates, which makes it easier to import project dependent coordinates
With these Starters, there is no need to configure (automatic configuration) and copy and paste dependent coordinates. All entry-level operations can be completed with one coordinate.
For example: for Web development, you only need to import the 'spring boot starter Web' coordinates


Of course, you can write your own pom file after building a maven project, or you can use spring initializer to generate the project with one click without writing your own configuration
Each Starter contains many necessary dependency coordinates under the current function. These dependency coordinates are necessary for project development, launch and operation. At the same time, these dependencies also support dependency transmission
There are many commonly used starters. For details, please refer to the link: SpringBoot-Starts

3.2 dependency management

Dependency management is the extraction and reuse of dependency coordinates. It is a function provided by Maven to uniformly manage the version of dependency coordinates.
My understanding is that Maven's dependency management function has been integrated into starter

3.3 automatic configuration

Encapsulate the configuration information into the AutoConfiguration class according to the requirements, and write the configuration information into the AutoConfiguration class in advance.
My understanding is: don't write a copy of configuration information such as ip and port number into the configuration file, but first specify the default value of the configuration information, that is, "agreement is greater than configuration", so generally don't modify it.

4. Configuration file of springboot

4.1 query configuration

Many SpringBoot configuration parameters have default values. There are two ways to query the default values:

  • Method 1: find it directly from the dependent jar package of the SpringBoot project

4.2 modify configuration

Although many configuration parameters of SpringBoot have default values, which are agreed to be greater than the configuration, sometimes it is unnecessary to modify some configuration parameters, so two ways are provided to modify the default configuration information:

  • (commonly used, in the form of pure key value pairs, only applicable to java language)
  • application.yml (can be used to describe objects, with certain simple syntax rules, slightly complex, applicable to all languages)
#properties file to modify the configuration

#port configuration
#Enable the debug mode and output the detailed log, which is a setting for development
#Configuration log: logging level. Specify the log under the package
#Configure context path
#yml file modification configuration

  port: 8888
    context-path: /demo

Property and yml file conversion tool: Conversion link

The syntax rules of yml file are as follows:

  • Case sensitive
  • The value must be preceded by a space as a separator
  • Use indents to indicate hierarchical relationships
  • Tabs are not allowed for indentation, only spaces are allowed, and the number of spaces indented is not important, as long as the elements of the same level are aligned to the left
  • #Indicates a comment
  • Arrays and collections use "-" to represent each element of the array
#A person has the attributes of name, age, address, city (multiple), pet (multiple pets, each pet is an object)
	name: haohao
	age: 31
	addr: beijing
        - beijing
        - shanghai
        - guangzhou
        - name: dog
          age: 2
        - name: tomcat
          age: 3
        - name: pig
          age: 5

In addition, the yml file also has the functions of "reference" and "generate random number"

#The name attribute in the person class refers to the value of the name variable
name: xiaoming
	name: ${name}
# Generate random string
my.secret: ${random.value}
# Generate random number
my.number: ${}
# The generated random number is less than 10
my.number.less.than.ten: ${}
# The generated random number ranges from 1024 to 65536 ${[1024,65536]}

4.3 configuration file injection Bean

  • Method 1: @ value annotation maps the value of the configuration file to the Bean attribute value managed by Spring

Features: convenient, but only one variable can be configured

  • Method 2: use the annotation @ ConfigurationProperties

5. Spring boot integrates Mybatis

5.1 summary of integration steps

  • Create a SpringBoot project and check MyBatis dependent coordinates
  • Create User table and entity User class in Mysql database
  • Write a three-tier architecture: Mapper, Service and controller, and write the method of querying all findAll()
  • Write the SQL statement of the method findAll() in Mapper interface
  • Profiles: database connection information
  • Access test address http://localhost:8080/queryUsers

5.1.1 create SpringBoot project and check MyBatis dependent coordinates:

5.1.1 create User table and entity User class in Mysql database:

#Mysql script to create database tables

`username` VARCHAR(50) DEFAULT NULL,
`password` VARCHAR(50) DEFAULT NULL,
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zhangsan', '123', 'Zhang San');
INSERT INTO `user` VALUES ('2', 'lisi', '123', 'Li Si');


/*Create User object*/
package com.lmy.pojo;

import lombok.Data;

public class User {
    private Integer id;
    private String username; //user name
    private String password; //password
    private String name;     //full name

5.1.3 write a three-tier architecture: Mapper, Service and controller, and write the method of querying all findAll(): write Mapper layer

mapper layer is an interface, or sql statements can be written directly on the interface file and annotated with @ Select (or other)

 * Inject the implementation class object of the current interface into the spring container
 * @Mapper = @Component = @Service = @Repository = @Controller

public interface UserMapper {
     * Query all
    @Select("select * from user;")
    List<User> findAll();

Alternatively, if you don't want to write the sql statement in the interface file, you can use xml file instead. The location of the xml file is as follows. The black bird is the logo used by Mybatis to write sql. It is a plug-in: mybatiscodehelper pro. The 7-day trial is free.

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper
        PUBLIC "-// Mapper 3.0//EN"
<mapper namespace="com.lmy.mapper.UserMapper">
    <select id="findAll" resultType="user">
        select *
        from user;
</mapper> write Service layer

The interface layer is relatively simple, and the service layer is written first

public interface UserService {
    List<User> findAll();

Then implement this interface. The implementation class of this interface can be generated automatically by IDEA instead of writing it manually:

The interface implementation class of the Service layer needs to use the @ Service annotation to identify the layer as the business layer, use the @ Autowired annotation to use the objects of the persistence layer, and use the methods of the persistence layer instead of new.

public class UserServiceImpl implements UserService {

    private UserMapper mapper;

    public List<User> findAll() {
        return mapper.findAll();
} writing Controller layer

Controller layer has no interface, @ RestController annotation = @ ResponseBody + @Controller

The function of @ ResponseBody is to convert java objects into json format data

Where @ Controller is used to process Http requests, @ Controller only defines a Controller class, and the method annotated with @ RequestMapping is the processor to process requests.

public class UserController {
    private UserService service;

     * Query all users
     * @return
    public List<User> findAll(){
        return service.findAll();

5.1.4 fill in the database connection information in the configuration file

In application Set the database information in the properties file and register the alias for the JavaBean, so that when writing the sql statement configuration file, the return value does not need to write the full class name of the class, even in lowercase

#Configuration database link information: database name, user name and password
#Register an alias for JavaBean, so that when writing the sql statement configuration file, the return value does not need to write the full class name of the class, even in lowercase

5.1.5 local access after configuration


6. Spring boot integrates Redis

It's very simple. Add the redis dependency in the pom file. Be sure to add it correctly, or you'll spend more than 3 hours to find the problem!


After the dependency is added, the business code is written, and the implementation logic is:

  • User sends request to query data
  • If the data exists in redis, it will be returned
  • If it doesn't exist, query from mysql. Before the query result is returned, save the result in redis
  • The key name of this data in redis is: "fully qualified class name + method name of service (in fact, it doesn't matter what name format. It can be uniquely identified and can be obtained every time you query)"
public class UserController {
    private UserService service;
    private RedisTemplate redisTemplate;

     * Query all users
     * @return
    private List<User> findAll(){
         * First, fetch data from redis cache: key, fully qualified name of service interface + method name
         * If it is returned to the user, if it is not returned to the user from mysql query, it will coexist with reids

        //The key value (fully qualified class name + method name) in redis. Value is the result of querying all users
        String key = service.getClass().getName() + "findAll";
        //Function return value, that is, user information
        List<User> users = null;
        //Fetch data from redis
        users = (List<User>) redisTemplate.boundValueOps(key).get();
        //If you don't get it, you can query the data from mysql and save a copy to the cache. If you find it, you can return it directly
            //There is no data in the cache. Go to mysql and save a copy of the result to redis
            users = service.findAll();
            System.out.println("Fetch data from database");
        }else {
            System.out.println("from redis Fetch data from cache");
        return users;


7 SpringBoot integration timer

Implementation steps

  • On the startup class, start the timer annotation (@ enableshcheduling)
  • Write timer method (@ Component + @Scheduled)
 * @EnableScheduling Enable the timer function support of springboot

public class Springboot04MybatisApplication {
    public static void main(String[] args) {, args);
public class TimerUtils {
    //Inject the interface implementation class object of the service layer
    private UserService service;

     * @Scheduled In addition to the cron expression property, you can also set the execution rules of the current method
     * cron Properties: setting general time rules
     * initialDelay: How long is the execution delay after initializing the current service
     * fixedDelay: How long after the last task is completed, the next task will be executed
     * fixedRate: Execute at a fixed frequency, regardless of the execution time of the previous task

    // Let the following code output the current time every 5 seconds
    //@Scheduled(cron = "0/5 * * * * ? ")\

    //Making the "display time" task execute every 2 seconds is more friendly than cron expression and makes up for the poor readability of cron expression, but cron expression is more powerful
    public void myTask2(){
        //Write business flow logic
        System.out.println(new Date());


8 send Http request

RestTemplate is used to send Http requests.
Spring's RestTemplate encapsulates HTTP based clients and is the HTTP client template tool class of Rest.

Achieve the following functions: after accessing an address, the server sends an http request to Baidu

  • Create a springboot project
  • Configure the object Bean of RestTemplate into the Spring container
  • Inject the RestTemplate object in the Spring container with @ Autowired in the test class
  • Send get request through getForObject of RestTemplate object

Configure the object Bean of RestTemplate into the Spring container:

public class Springboot04MybatisApplication {
    public static void main(String[] args) {, args);
    //Inject RestTemplate object into Spring container

    //The RestTemplate object injected into the spring container is written in the boot class because the boot class itself is also a configuration class. Of course, you can also write a configuration class yourself
    public RestTemplate restTemplate() {
        return new RestTemplate();

After accepting the request from the browser, the server sends a request to Baidu and responds to the browser

public class HelloController {
    private RestTemplate restTemplate;

    public String sendHttpRequest(){
         * Methods corresponding to different Http request modes
         * get: getForObject()
         * post: postForObject()
         * delete: delete
         * put: put
        //Send get request
        String responseBody = restTemplate.getForObject("", String.class);
        return responseBody;

9 test

It is convenient to use annotations on this class for testing. For springboot 2 2. In previous versions, the test class needs to write two notes:

  • @RunWith(SpringRunner.class): initialize the test class, springboot2 Not since version 2
  • @SpringBootTest: indicates that the current class is a spring test class

The following test class code tests the http get request method of RestTemplate class

public class Springboot04MybatisApplicationTests {

    private RestTemplate restTemplate;

     * The RestTemplate is used to test whether the http get request can succeed
    public void contextLoads() {
        String forObject = restTemplate.getForObject("", String.class);
        System.out.println("Hello 1 aaaa");

10 spring boot packaged deployment

10.1 jar package deployment

Now the method of making jar packages is popular (you don't need to write a special class for deployment, jar packages can be executed directly, and you don't need your own Tomcat environment).

The traditional packaging method is to make war package (write a class yourself, and use your own Tomcat running environment to run war package).

The steps of converting the SpringBoot project into a jar package are as follows:

  1. Open Maven Toolkit - > lifecycle - > package on the right side of IDEA
  2. Note the packaging type of the project pom file, which is jar by default or manually identified as jar: < packaging > jar < / packaging >,
  3. Note that the project pom file must have maven plug-in: spring boot maven plugin (make the current spring boot project into an executable jar package)
  4. After packaging, there is a project jar package in the Target file of the project. Copy it to a path, such as disk d
  5. Open the windows command line window and enter the following startup instructions. At this time, the whole project will be started.

1 out of 3 start command

  • Basic instruction: java -jar target/day01_springboot_demo01-1.0-SNAPSHOT.jar
  • The specified web port number is attached when starting: java -jar target/day01_springboot_demo01-1.0-SNAPSHOT.jar --server.port=8081
  • Set the memory occupied by the project at startup (20-80Mb): java -Xmx80m -Xms20m - jar target/day01_springboot_demo01-1.0-SNAPSHOT.jar

Note: the reason why the configuration parameter of the second instruction (the port number directly configured during deployment is 8081) can take effect is that the parameter "args" is passed in when the spring boot project starts the run method call in the main function of the boot class. Otherwise, it will not take effect!

10.2 # war package deployment

Making war package deployment is a traditional method (you need to write a class yourself, and you need to run war package with your own Tomcat running environment). The steps are as follows:

  1. Determine the packaging type of project pom file as: < packaging > war < / packaging >
  2. Registered startup class, details are as follows
  3. Maven tool packaging project on the right side of IDEA
  4. Copy the project war package to the webapps directory of Tomcat
  5. Double click under the bin directory where Tomcat is running bat
  6. Access (when accessing, the access path should be prefixed with the name of the project war package under the webapps directory at the beginning!)

Register startup class
The registered startup class is a class written by ourselves. As the entry of the war package, it is placed at the same level as the controller package
Registering a startup class is a standard way to write it. You only need to The parameters in the sources() method can be changed to the bytecode file object of the boot class of the SpringBoot project)

 * war Package, program entry
 * Equivalent to WEB-INF / Web XML configuration file
public class ServletInitializer extends SpringBootServletInitializer {
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
         * Parameter: bytecode file of SpringBoot boot boot class
        return builder.sources(Springboot02FasterApplication.class);

11 precautions

Maven version should not be lower than 3.5. Originally, I wanted to use my own warehouse. My Maven version is 3.3.9. It may be that the version problem always leads to errors when importing pom files (especially when importing redis dependent packages), so I now use the local warehouse in the default configuration and want to change to my own custom warehouse in the future.









Topics: Java Mybatis Redis Spring Boot IDEA