Table of contents
1. Quick start with springboot
2.Introduce starting dependencies
2. Shortcut to create springboot project
1. Relationship between configuration files
3. Three ways to read configuration files
1. First inject through @Value annotation
2. Injection through Environment
3. Pass @ConfigurationPropertis
2.profile configuration method
1.Multiple profile file configuration
5. Loading order of internal configuration files
6. Run with specified parameters on the command line
7. Springboot integrates other frameworks
2.Introduce redis starting dependency
4. Change the location of the connection to redis
2. Create a project and introduce starting dependencies
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.
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.
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
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)
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.
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!";
}
}
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.
Start testing, click on the startup class to start the springboot project.
3. Configuration file
1. Relationship between configuration files
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
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.
4.profile
1 Introduction
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.
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
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
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.
3.Profile activation method
1.Virtual machine parameters
Right click and select Edit Configuration.
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.
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.
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
You can see that there is the jar package we created in the target directory of the current module.
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) .
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.
5. Loading order of internal configuration files
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.
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.
7. Springboot integrates other frameworks
1. Integrate junit
1. First create a project,
Create a class as shown below.
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.
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
2. Integrate redis
1. Implementation steps
2.Introduce redis starting dependency
We can introduce redis directly when creating the project, select NoSQL, and select the first one
After creation, we can see the redis dependency in the pom file
3. Test it
The directory structure is as follows
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.
We can see that the connection is still normal.
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
2. Create a project and introduce starting dependencies
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!