"Springboot Usage" - just for use, one article is enough

Table of contents

 

environment:

spring boot overview

1. Quick start with springboot

1. Create a maven project

2.Introduce starting dependencies 

3. Custom controller

4.Write startup class 

5. Start testing 

2. Shortcut to create springboot project

 Replenish

 3. Configuration file

1. Relationship between configuration files

 2.yml configuration file

1. Basic grammar

 2. Specific implementation

3. Three ways to read configuration files 

1. First inject through @Value annotation

 2. Injection through Environment

 3. Pass @ConfigurationPropertis

4.profile

1 Introduction

2.profile configuration method

1.Multiple profile file configuration

2.yml multi-document method

3.Profile activation method

1.Virtual machine parameters

2. Command line activation

 5. Loading order of internal configuration files

 6. Run with specified parameters on the command line

 7. Springboot integrates other frameworks

1. Integrate junit

 2. Integrate redis

1. Implementation steps

2.Introduce redis starting dependency

3. Test it

4. Change the location of the connection to redis 

3. Integrate Mybatis

1. Steps

2. Create a project and introduce starting dependencies

 3.Write configuration file

at last


 

environment:

1.idea2021

2.java8

3.springboot 2.6.13

spring boot overview

Spring Boot is a new framework provided by the Pivotal team. It is designed to simplify the initial construction and development process of new Spring applications. The framework uses an ad hoc approach to configuration, eliminating the need for developers to define boilerplate configurations.

Spring Boot is developed based on Spring. Spring Boot itself does not provide the core features and extended functions of the Spring framework. It is only used to quickly and agilely develop a new generation of applications based on the Spring framework. With the core idea of ​​​​convention over configuration, Spring Boot helps us make a lot of settings by default. Most Spring Boot applications only require very little Spring configuration and can be used out of the box with almost zero configuration.
 

1. Quick start with springboot

1. Create a maven project

Choose to use maven to create the project, go to the next step, then name the project and click Finish.

f64479e83e5a4d839666d16c2600740a.png

2.Introduce starting dependencies 

    <!--springboot工程需要继承的父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
    </parent>

    <dependencies>
        <!--web开发的起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

3. Custom controller

Define a controller at will for testing.

08ebb8feb23544e0a3e513b414f4986e.png

For the controller layer, what is worth mentioning here is the difference between the @Controller and @RestController annotations . @Controller controller, handles http requests. The @RestController annotation is equivalent to @ResponseBody+@Controller combined. The effect of RestController is to display the object returned by the method directly in json format on the browser.

package com.itheima.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return " hello Spring Boot !";
    }
}

4.Write startup class 

The startup class is the entrance to the springboot project. We are used to ending with Application.

@SpringBootApplication
public class HelloApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class,args);
    }
}

5. Start testing 

We click on the startup class to start the project, and then we can access it at the browser address.

We can see this port number on the command line after running

f4526a203ed54eb9af8a8c6775d5b83d.png

42f6eb48e3a64fc89f3c8b2fd110d318.png

Supplement: In fact, idea provides a simpler way to create a springboot project, which we will talk about below.

 

2. Shortcut to create springboot project

First select Spring Initalizr, and then select the server. The default here is a URL such as start.spring.io, but we know at a glance that this is a foreign URL, because the first-level domain names we see in China are generally .cn or .com (not much to say, it’s not important here), so we can use domestic servers. In China, Alibaba Cloud provides the same service, the website is: start.aliyun.com, so we Change the service URL to start.aliyun.com. Then write the project name and click Next.

Note: Why do we choose the URL here? In fact, it is because creating a springboot project requires an Internet connection to download relevant modules (there are also methods on the Internet that do not require an Internet connection. Since I have not tried it, it is difficult to say)

693ba21843de4ae69d1135fb58225162.png

 

Next, add dependencies. Here we can choose a Mysql driver, and then choose a web spring web dependency. What if we forget to add some dependencies? right! We can add it in the pom.xml file ourselves later.

1574ee4760cf4ac3b1058af7819d546f.png Then, we can see that there is our startup class in the springbootinit directory for startup dependencies and automatic configuration. We create a HelloController class under springbootinit for testing.

package com.itheima.springbootinit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {


    @RequestMapping("/hello")
    public String hello() {
        return "hello Spring Boot 222!";
    }
}

365d7adeb7f347db88d2a02986471ce8.png

 Replenish

But in fact, in the formal development environment, we will create the controller, dao, and service packages in the same directory as the startup class, and then create the class LoginController under the controller package, as shown below.

Note: The startup class must be in the same directory as the controller, dao, and service packages, because the startup class will automatically scan packages in the same directory as itself by default.

915570d3c2524a679adaee4d09082686.png

Start testing, click on the startup class to start the springboot project.

1dc23ccebd964f66a7d1d57b08c2b6ff.png

 3. Configuration file

1. Relationship between configuration files

2fb0c761e55f4acaaa9577f71144a615.png

In the springboot project, we can modify the default configuration of springboot through the following two configuration files. But when we have multiple configuration files, we will give priority to the configuration information in the configuration file with higher priority. However, if the configuration information of the low-level file is not defined in the high-level configuration file, then springboot will still read it. Obtaining low-level configuration file information actually means that springboot will read all configurations, no matter what level of configuration file it is.

For example, in the properties configuration file:

server.port=8089

And in the yml configuration file:

person:
  name: zhangsan
  age: 20
  address:
  - beijing
  - shanghai

server:
  port: 8082

Then, springboot will use the port information in the properties configuration file, but since the person information is not defined in the properties configuration file, springboot will use the person information in yml. 

 2.yml configuration file

1. Basic grammar

e924869e186244ba80210537697b47af.png

 2. Specific implementation

#参数引用
name: nihao
#对象
person:
  name: ${name}
#  name: zhangsan
  age: 20
#对象行内写法
person2: {name: zhansang,age :20}
#数组
address:
  - beijing
  - shanghai
#数组行内写法
address1: [beijing,shanghai]

#纯量
msg1: 'hello \n world' #不会识别转义字符
msg2: 'hello \\n world' #会识别转义字符

server:
  port: 8082

3. Three ways to read configuration files 

1. First inject through @Value annotation

    @Value("${name}")
    private String name;

    @Value("${person.name}")
    private String name2;
    //注意对象和基本数据类型的注入方式的不同

 2. Injection through Environment

First define an Environment object in the class and add the @Autwired annotation. In this case, springboot will inject the Environment object when the project is initialized.

    @Autowired
    private Environment env;

Use the .getProperty() method to call the value of the configuration file. 

        System.out.println(env.getProperty("person.name"));
        System.out.println(env.getProperty("address[0]"));

 3. Pass @ConfigurationPropertis

As shown below: But in fact, it doesn't matter if prefix = "person" is not added here, at least no error will be reported, but what it obtains is data other than person, rather than obtaining data from the person we defined in the properties configuration, that is: Disobey

person:
  name: ${name}
#  name: zhangsan
  age: 20

Get data from. Instead, the data is obtained from somewhere other than the profile person data. 

ca8bfc2bf2744252971861c2b1d4aa72.png

4.profile

1 Introduction

8393c2cfb0cf4ebf8b1839252e7ea5da.png

2.profile configuration method

1.Multiple profile file configuration

First, let's create the configuration files, application-dev.propertis (production environment), application-pro.propertis (development environment), application-test.propertis (test environment). There is no need to create a yml file here.

d9814a3e0c4244e791f58a08bba2614c.png

Then we specify the environment in each configuration file. For example, test.properties uses 8082, and pro.properties

8083 is used, dev.properties is 8081

39fac037c8154898af50b37c86e9ea0c.png Then we activate the production environment in the application.properties configuration file. If neither is activated, then the default production environment 8080 is still used. Now we activate dev

spring.profiles.active=dev
#spring.profiles.active=pro
#spring.profiles.active=test

 1b000033f4184157b028e82dcc531d30.png

You can see that the activation is successful. 

2.yml multi-document method

---

server:
  port: 8081

spring:
  profiles: dev
---

server:
  port: 8082

spring:
  profiles: test
---
server:
  port: 8083

spring:
  profiles: pro
---
#激活配置
spring:
  profiles:
    active: dev

For example, now I use test, and when I run it, I find that the activation is successful.

b0f8bc567513465fac39cc4b6ea8187f.png

3.Profile activation method

1.Virtual machine parameters

Right click and select Edit Configuration.

0d59460ceef84114a4644b48c3a6a160.png

1. In the virtual machine options, write -Dspring.profiles.active=test. Be careful not to write the following program parameter configuration first. Afterwards we will find that the test configuration file takes effect.

016f037e3aab4a5e87570359384dd38a.png

 2. As shown in the picture above, we write --spring.profiles.active=pro in the configuration file of the program parameters (do not write it at the same time as the above virtual machine parameters), then we start, and we can find that the pro configuration file is activated.

2. Command line activation

During our actual testing and online deployment, there is no graphical tool like idea, so we need to activate the configuration file through the command line, but the premise is that we must first package the springboot project into a jar package.

1. Make jar package

Select our project, then start packaging, click package.

4bf49536f72447f7bf7ef50a7b1684df.png

Interlude: When I built the jar package here, an error occurred: Unable to find main class

The solution is to add the following configuration in the plug-in <artifactId>spring-boot-maven-plugin</artifactId>, which actually adds the startup class, because the error means that the startup class was not found.

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.itheima.springbootprofiles.SpringbootProfilesApplication</mainClass>
                </configuration>
            </plugin>
        </plugins>

2. Packaging successful

137b36485bad46d4b77b08eedb77e999.png

 You can see that there is the jar package we created in the target directory of the current module.

785b4a7903e14e08957362075bbd8be6.png

Then we hold down shift+right click, click on the powershell file, and then enter java -jar .\springboot-profiles-0.0.1-SNAPSHOT.jar, and press Enter to run successfully. (Note that you must stop the projects in the idea here first, otherwise there may be port occupation problems) .

511fac7ebd8d4c05ac611ce505556970.png

3. Enter the activation command on the command line

输入java -jar .\springboot-profiles-0.0.1-SNAPSHOT.jar --spring.profiles.active=pro

As shown in the picture below, we can see that the pro configuration has taken effect.

dc429da953c543508f8f942a3167cff3.png

 5. Loading order of internal configuration files

4582fd52956a40368e588a9303ef9f5b.png

This file is your project, and the classpath can be understood as the Java and resource parts of the project before packaging. For example, now we create the following module springboot-config, and then add the following configuration. As shown in the picture below, you can see that there is a properties configuration file under file, so its priority is second. There is also a config folder under file. The priority of the properties configuration file in the folder is first, and then the config under resource The priority of the configuration file in the folder is third, and the priority of the configuration file under resource is fourth.

ba957b32ff0a4a29b50359f5ac41c426.jpeg

But it is worth noting that file: configuration file and file:/config/config file will not be entered into the jar. Therefore, after the project is packaged into a jar package, the configuration files in the resource/config directory will take effect first, followed by the configuration files in the resource directory .

 6. Run with specified parameters on the command line

Enter java -jar .\springboot-profiles-0.0.1-SNAPSHOT.jar --server.port=9090 as shown below. --server.port=9090 is the parameter we temporarily specified.

b503ab0cfe474bb49ab22eb832c6369e.png

 7. Springboot integrates other frameworks

1. Integrate junit

1. First create a project,

Create a class as shown below. 

481c50d154874a948b96561e58a6fefb.png

Userservice

package com.itheima.springboottest;

import org.springframework.stereotype.Service;

@Service
public class UserService {


    public void add() {
        System.out.println("add...");
    }
}

UserServiceTest

package com.itheima.test;

import com.itheima.springboottest.SpringbootTestApplication;
import com.itheima.springboottest.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * userService的测试类
 */

@RunWith(SpringRunner.class)
//当测试包和启动类在同一包下,下面的注解是不需要指定的
@SpringBootTest(classes = SpringbootTestApplication.class)
public class UserServiceTest {

    @Autowired
    private UserService userService;
    //注意,要对测试方法加上@Test注解
    @Test
    public void testAdd() {
        userService.add();
    }
}

 When the test package and startup class are in the same package, the following annotations do not need to be specified. For example, if I put the test class and startup class in the same package, then I do not need to add @SpringBootTest(classes = SpringbootTestApplication.class) this note.

377ad51c3102447398e19b2a23ab242c.png

Next test method

package com.itheima.springboottest;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * userService的测试类
 */

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @Test
    public void testAdd() {
        userService.add();
    }
}

 Note: After junit5, there is no need to add the @RunWith annotation.

Click on the test method and it runs successfully

2becd0aaa35c4baeadc73112e7996a61.png

 2. Integrate redis

1. Implementation steps

80443d6825ed4623a78463dd94317113.png

2.Introduce redis starting dependency

We can introduce redis directly when creating the project, select NoSQL, and select the first one

efa1f64149a44515b70dd279281c5ca0.png

After creation, we can see the redis dependency in the pom file

5dedabda34e04cb1aad4856bc6a32a02.png

3. Test it

The directory structure is as follows

81806d5992524eeeb42521bcec91da68.png

Create the test class SpringbootRedisApplicationTest

package com.itheima.springbootredis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootRedisApplicationTests {
    //注入redis
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testSet() {
        //存入数据
        redisTemplate.boundValueOps("name").set("zhangsan");
    }

    @Test
    public void testGet() {
        //获取数据
        Object name = redisTemplate.boundValueOps("name").get();
        System.out.println(name);
    }

}

By default, springboot will provide a redis when redis is not started on your local machine or there is no redis service. However, if redis exists on your local machine and the redis service is turned on, then the local redis will be used to access data, such as Say I have already started redis on this machine.

b44bd5bd585a49b7af080d879b6d0c34.png

We can see that the connection is still normal.

4ca93155cb6a4f71a497947e5de71fe3.png

4. Change the location of the connection to redis 

We can create a configuration file to specify the location where we connect to redis

spring:
  redis:
    host: 127.0.0.1 # redis的主机ip
    port: 6379

In this case, we can connect different redis services. 

 

3. Integrate Mybatis

1. Steps

51de0bedb28a40f799f960728d0634b4.png

 

2. Create a project and introduce starting dependencies

4cdf5568eefc4d9f93c6426e724710eb.png

 3.Write configuration file

Configuration yml file

# datasource
spring:
  datasource:
    url: jdbc:mysql:///springboot?serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver


# mybatis,如果你是基于注解开发的,那么下面的配置是不用加的
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml # mapper映射文件路径
  type-aliases-package: com.itheima.springbootmybatis.domain

  # config-location:  # 指定mybatis的核心配置文件

So what is annotation-based development, that is, there is no mapper.

UserMapper interface

package com.itheima.springbootmybatis.mapper;

import com.itheima.springbootmybatis.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserMapper {

    @Select("select * from t_user")
    public List<User> findAll();
}

 Assuming you are not developing based on full annotations, then you need xml files.

UserMapper.xml

<?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">
<mapper namespace="com.itheima.springbootmybatis.mapper.UserXmlMapper">
    <select id="findAll" resultType="user">
        select * from t_user
    </select>
</mapper>

 Then we need to configure our Mapper information in the yml configuration file.

# datasource
spring:
  datasource:
    url: jdbc:mysql:///springboot?serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver


# mybatis
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml # mapper映射文件路径
  type-aliases-package: com.itheima.springbootmybatis.domain

  # config-location:  # 指定mybatis的核心配置文件

 

at last

This blog will introduce the use of springboot here. If this blog is helpful to you, please give it a like and support it. Thank you! See you in the next blog!

 

Guess you like

Origin blog.csdn.net/weixin_64972949/article/details/131107879