SSM(Spring Spring MVC MyBatis) has made our development very simple, but there are still some problems. First, as the project expands, the Spring configuration file will be a little big. Of course, we can split it, but the injection between the complex dependencies managed by IOC doesn’t seem to change much. We know that each JAR package has a dependency relationship, and the same JAR package may depend on different JARS. We need to be careful when developing, lest the wrong version may lead to project problems. These issues will be addressed by Spring Boot.

preface

In today’s Java field, Spring Boot is very popular, because it is really fast and easy to develop with it. Some people even say that you can learn Spring Boot directly without learning Spring, but the bottom layer of Spring Boot is still Spring Framework. It’s just a layer of encapsulation on top of the Spring Framework (as far as I’m concerned). Learning Spring Boot without learning Spring is like building a second layer without building a foundation. So I want you to know something about the Spring Framework before you read this article, so how do you make sure you meet this standard? Check out my blog: Welcome to the Spring Era (I) IOC biography. If you know everything about this blog, you can basically understand what this blog is about.

I have posted all these exercises on the code cloud, and I will post one on GitHub when I have time. The address is as follows:

  • Gitee.com/cxk6013/spr…

Introduction to the

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”.

If you want to create a single, production-level Spring-based application, Spring Boot is so simple that you don’t need to write any code, just run it.

We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need minimal Spring configuration.

We designed a view for the Spring platform and third-party libraries so that developers can get off to a fast start. Most Spring Boot programs require very little configuration. The second understanding is that we re-examine the relationship between the Spring platform and third-party libraries to design the Spring Boot framework, Spring Boot can allow developers to develop quickly, most of the Spring Boot programs need few configuration files. Both are similar in meaning to get developers to market quickly and with few configuration files. If you are good at English, you can leave a message below.

The view above is what I understand to be this thing:

The characteristics of

  • Create stand-alone Spring applications

Create a single Spring program

  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)

Built-in Tomcat, Jetty, Undertow and other application servers (you can choose by yourself)

  • Provide opinionated ‘starter’ dependencies to simplify your build configuration

(Provides starter dependency sets that you can choose to make your POM files smaller)

  • Automatically configure Spring and 3rd party libraries whenever possible

Automatically configure Spring and third-party libraries whenever possible

  • Provide production-ready features such as metrics, health checks, and externalized configuration

Provide a ready-to-use production environment feature, like a metric, for health monitoring and extended configurations. Spring Boot Admin monitors application health

  • Absolutely no code generation and no requirement for XML configuration

No derivative code and no XML configuration files at all

What is starter? What is automatic configuration? How can I configure database information without XMl configuration files? Take your time and follow my train of thought as I explain these nouns one by one.

Spring Boot and Spring Cloud

Spring Boot seems to be wrapped up in the concept of microservices. Is that what Spring Boot is for? At this point, some students may ask, what are microservices? To put it simply, microservices is a software architecture. What is software architecture? Please refer to my post:

  • Talk about software architecture

If you often read my articles, you will find that my articles are basically linked one by one, which is an orderly system.

What is Spring Cloud?

Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems Spring Cloud provides developers with a set of tools to solve common problems encountered in building distributed systems. It turns out to be a toolset, and it doesn’t seem to have anything to do with microservices. Don’t worry, let’s look for it on the Spring website.

Microservice architectures are the ‘new normal’. Building small, self-contained, Ready to run applications can bring great flexibility and added resilience to your code. Spring Boot’s many purpose-built features make it easy to build and run your microservices in production at scale. Microservices architecture is becoming the new normal, and building small, container-containing, easy-to-run systems gives your system flexibility and scalability. Many of Spring Boot’s build features make it easy for developers to build and deploy microservices in large projects.

And don ‘t forget, No Microservice architecture is complete without Spring Cloud — Easing Administration and Boosting your fault-tolerance. But don’t forget that in the Java world, any microservices architecture without Spring Cloud is incomplete due to the lack of fault tolerance and administrative headaches.

Therefore, Spring Boot and Spring Cloud can be used to build microservices and realize microservice architecture. Spring Boot is used for development services, just to speed up your development of Spring applications, not necessarily for microservices. Spring Cloud for service governance and Spring Boot can be seamlessly integrated. The relationship between the two should be made clear at this point.

How to create a Spring Boot project

The version number is optional

See this question from Zhihu: How is the version number of the software determined? Direct to see the official agreement, please go to this website: semver.org/lang/zh-CN/ here is the English version number, like GA and so on:

  • GA

General Availability, official release version, officially recommended for widespread use, some foreign countries use GA to denote release version.

  • RELEASE

Official release, the official recommended version, sometimes indicated by GA. Such as spring.

  • Stable

Stable. Some open source software will use stable to refer to its official release. For example, Nginx.

  • Final

The final version is also a representation of the official release. Such as Hibernate.

  • RC

Release Candidate: basically no new features, mostly bug fixes. Is the final release into the official version of the previous version, the bug can be released into the official version.

  • alpha

Alpha is the first Greek letter, indicating the earliest version, the internal beta version, generally not released to the outside, more bugs, incomplete features, generally only used by testers. Beta

Beta is the Greek letter, the second open beta, later than alpha version, there will be “fans” test mainly use, this version there are still a lot of bugs, but stable than alpha version. This phase of the release will continue to add new features. It is divided into Beta1, Beta2, etc., until it gradually stabilizes and enters the RC version. We cover the common ones, and then there are a few, see the articles in Resources below for more information.

Method 1: Spring Initializr

Do not configure Tomcat, directly run let’s see the effect:Then let’s try writing a Controller:The code is as follows:

RestController
public class HelloWorld {
    @GetMapping(value = "/hello")
    public String test(a) {
        return "hello"; }}Copy the code

Enter the url:http://localhost:8080/helloResults:Now what I’m going to do is I’m going to write controllers without having to do all this stuff.

Method 2: Introduce dependencies directly

  1. Create a New Maven project. If you don’t know anything about Maven, please read: Maven Learning Notes
  2. Spring Boot in 2.3.9 removes the poM display corresponding to starter. If you want to copy it, you can go to this url:

Docs. Spring. IO/spring – the boot…

Several attempts were made to access the POM to GitHub, but always failed. Spring Boot’s starter dependency always starts with spring-boot-starter. We don’t need to write the version number because we inherit the parent dependency. Let’s just write it like this:

<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
Copy the code

Then create a package and class:

@SpringBootApplication
public class StudySpringBoot {
    public static void main(String[] args) { SpringApplication.run(StudySpringBoot.class, args); }}Copy the code

Running results:The same controller code:

The same result:

Analyze this Hello World

We’ve already built a Spring Boot project in two ways. We’ve built a Web project very quickly. All the cumbersome configuration of Spring MVC has been thrown away and we can start development very quickly. How does this work? Let’s take a look.

Pom files become smaller

Then maybe some students here will ask, I don’t need so much ah, you introduced to me, is not affecting my boot speed? Don’t worry, this is an on demand import, Spring Boot will automatically import on demand based on the starter you introduced in your POM, let’s take a look at the Web starter we introduced.

So you don’t have to worry about everything that’s introduced by a parent dependency being introduced. Spring Boot makes our libraries and development scenarios into a starter. We don’t need to bother to introduce them one by one when developing them. For example, if you are developing web programs, you can find web-starter.

This way we only have to select the starter based on the scenario, so we don’t have to worry about the jar version mismatch. This is also the third feature of Spring Boot mentioned above: Provide opinionated ‘starter’ dependencies to simplify your build configuration. Provide starter to make your POM files simpler.

Principle of automatic configuration

Let’s look at why we can write Controller directly without configuring DispatchServlet, scanning package, annotation driver and other Spring MVC configurations. In fact, we can guess that we do not need Spring Boot to configure it for us. This is also called automatic configuration. Here I paste the startup program:

@SpringBootApplication public class BootApplication { public static void main(String[] args) { SpringApplication.run(BootApplication.class, args); }}Copy the code

This is a normal main function, so we’ll start with the @SpringBootApplication annotation above.

Then we see three notable notes:

  • @ComponentScan

Welcome to The Spring Era. Before you learn Spring Boot, it is necessary to learn Spring. I figured out why the autoscan didn’t work.

  • @EnableAutoConfiguration

@ EnableAutoConfiguration overview:

@EnableAutoConfigurationTwo more custom annotations were found:

@ AutoConfigurationPackage / / will AutoConfigurationImportSelector this class join the IOC container @ Import (AutoConfigurationImportSelector. Class)Copy the code

AutoConfigurationImportSelectorThis class is probably the one that introduces this functionality on demand based on the starter implementation. We study the AutoConfigurationImportSelector this class:Remember Deferred, remember the ImportSelector interface? The value returned by the selectImports method of the interface can then be added to the IOC container. If you don’t remember, look againWelcome to the Spring era. Let’s continue with the point of interruption:

Note also don’t know is the IDEA of a bug or what’s the matter, I in 99 lines of breaking point, startup into do not come, but I’m getAutoConfigurationEntry this method breaking point came in, I was very strange, is it high version of the Spring change the Boot process? However, after watching a lot of videos, I found that the interruption point was ok, so I finally determined that my IDEA was the problem. Let’s move on:

It’s WebMvcAutoConfiguration that finally takes care of the auto-configuration. Let’s take a look at this class:

There are five new Spring Boot custom annotations:

@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
		ValidationAutoConfiguration.class })
Copy the code

So let’s start with the three @conditionalon’s, which is sort of like conditional annotations, right, it’s essentially conditional annotations. If you click on it, you can find @Conditional in it and you don’t even have to read the annotations to see it in the name:

  • @ConditionalOnWebApplication: is a Web application that meets the criteria if it introduces dependencies with servlets.
  • @ConditionalOnClass:Class, dispatcherservlet. class, WebMvcConfigurer. Class
  • @ConditionalOnMissingBeanThe IOC container is injected only if the attributes of this class are missing.

Together these three conditions hold up, automatically load WebMvcAutoConfiguration, and then start automatic configuration. Just to add, where do these auto-configuration classes come from? Let’s think about it, we can’t write it in code, so I’ll just write it without adding an auto-configuration class. Actually this is also in the configuration file, or in AutoConfigurationImportSelector selectImports method:

There is always some metadata that a program needs to get from a configuration file. Then we look at the @AutoConfigurationPackage annotation, which basically gives us a clear understanding of how Spring Boot is automatically configured.Let’s interrupt to see what this class does:

Then let’s look at the comments on the AutoConfigurationPackage:

Registers packages with {@link AutoConfigurationPackages}. When no {@link #basePackages

base packages} or {@link #basePackageClasses base package classes} are specified, the package of the annotated class is registered. When base Packages or Base Package classes are not specified in the @AutoConfigurationPackage attribute, the package or subpackage classes of the annotated class with corresponding annotations are added to the IOC container. Doesn’t this overlap with the @ComponentScan annotation? See I said don’t understand this, I wonder if the wrong @ ComponentScan annotation role, I’m going to look at the comments of the AutoConfigurationPackages this class:

Class for storing auto-configuration packages for reference later (e.g. by JPA entity scanner).

This class stores references to auto-configuration packages for later reference, such as JPA entities corresponding to scanners. I don’t know why,

To summarize

Now we have a general understanding of why Spring Boot does not need to configure a lot of Servlet to do the Web, because Spring Boot’s automatic configuration class already does this for us. Spring Boot determines which auto-configuration class to enable based on conditional annotations and starter. The reason why it makes our POM smaller is because Spring Boot turns our development scenario into a starter, and if we want to develop the Web, we need to introduce a Web starter first. If it’s MyBatis, there’s MyBatis – Starter. Spring Boot execution flowchart:

Configuration files that cannot be discarded

Although we did a lot of automatic configuration, which greatly reduced the size of the Spring Boot configuration file, there were always some configurations we didn’t want to hardcode, such as database connections, ports, and so on. So Spring Boot also provides a way to load configuration files. Spring Boot supports a new configuration file, called YAML, which expresses K and V pairs by indenting them, and requires a space between K and V. Spring Boot currently supports two main configuration files:

  • Application. The properties of k, v
  • Application. Yml indentation

By default, application.properties takes precedence over application.yml.

@ConfigurationProperties

We are currently using org. Springframework. Boot. Autoconfigure. Web. ServerProperties to explain the thought of Spring boot loading the configuration file, let’s have a look at this class:

@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true) public class ServerProperties { /** * Server HTTP port. Port */ private Integer port; /** * Network address to which the server should bind. Address */ private InetAddress address; @NestedConfigurationProperty private final ErrorProperties error = new ErrorProperties(); /** * Strategy for handling X-Forwarded-* headers. */ private ForwardHeadersStrategy forwardHeadersStrategy; /** * Value to use for the Server response header (if empty, no header is sent). */ private String serverHeader; /** * Maximum size of the HTTP message header. */ private DataSize maxHttpHeaderSize = DataSize.ofKilobytes(8); /** * Type of shutdown that the server will support. */ private Shutdown shutdown = Shutdown.IMMEDIATE; @NestedConfigurationProperty private Ssl ssl; @NestedConfigurationProperty private final Compression compression = new Compression(); @NestedConfigurationProperty private final Http2 http2 = new Http2(); private final Servlet servlet = new Servlet(); private final Tomcat tomcat = new Tomcat(); private final Jetty jetty = new Jetty(); private final Netty netty = new Netty(); private final Undertow undertow = new Undertow(); }Copy the code

There is also a static inner class in ServerProperties. Let’s take a look at it, and I’ll paste some of the source code directly here:

	public static class Servlet {
    /** * Servlet context init parameters. */
		private final Map<String, String> contextParameters = new HashMap<>();

		/** * Context path of the application. */
		private String contextPath;

		/** * Display name of the application. */
		private String applicationDisplayName = "application";
}
Copy the code

Note that there is a @configurationProperties annotation. If we look at the annotation, we should not be surprised to see that there are only so many common words for development.

Annotation for externalized configuration. Add this to a class definition or a @Bean method in a @Configuration class if you want to bind and validate some external Properties (e.g. from a .properties file).

This annotation is used to import external Configuration files. Specifically, if you want to set some values from external files (such as the Properties Configuration file) for Configuration classes or Configuration class Java beans (i.e., @Configuration classes, @Bean annotations), Then you can use this annotation.

Although Spring Boot has minimized configuration files, some configuration files still need to be imported, and how to bind them to the corresponding object is through the @configurationProperties annotation.

Binding is either performed by calling setters on the annotated class or, if @ConstructorBinding is in use, by binding to the constructor parameters.

The binding is done by calling the annotated class’s method through the set method, or by using the @constructorBinding constructor if it has one.

If there is @constructorbinding, call the ConstructorBinding value, if not, call the Set method.

Note that contrary to @Value, SpEL expressions are not evaluated since property values are externalized.

Note that the SpEL expression does not evaluate this additional configuration as opposed to the @Value annotation. The @value expression is a Spring EL expression.

So the question is, how do we match? How do I have all these attributes that correspond to the values in the configuration file? The @configurationProperties annotation is a syntax candy. This is a bit of advanced Java knowledge. I assume you already know Java.

The answer is the value property in @ConfigurationProperties. The alias is prefix, which means prefix. So the rule for matching is the prefix plus the attribute name. The @configurationProperties prefix is “Server”, which has a port property, so we should say “Properties” :

server.port=8884
server.servlet.context-path=/studyBoot
Copy the code

Let’s start the project and see if the configuration is successful:The configuration method in YAML is indented with Spaces:

server:
  port: 8882
  servlet:
    context-path: /study
Copy the code

Yaml is equivalent to putting propertis in. Instead of indentation, the = sign becomes a space. Pay attention to this rule. ServerProperties has other properties that I won’t go into here. Let’s do a few more connections to see how the @configurationProperties annotation can be used.

@getter // Lombok plugin @setter // Lombok plugin @noargsconstructor // Lombok plugin @toString // Lombok plugin @component @ConfigurationProperties(prefix = "student") public class Student { private int age; private String name; private boolean sex; private String[] locations; private StudentCard car; } @NoArgsConstructor @Setter @Getter @ToString public class StudentCard { private String cardNo; }Copy the code

Configuration in YAML:

student:
 age: 23
 name: zs
 sex: true
 locations:
   - Shanghai
 car:
   cardNo: 8888
Copy the code

Let’s test it out:

@RunWith(SpringRunner.class)
@SpringBootTest
class BootApplicationTests {
	@Autowired
	private Student student;
	@Test
	void contextLoads(a) { System.out.println(student); }}Copy the code

Test results:

Usually write yamL by indenting is also a headache, fortunately IDEA has strong hints, but sometimes I prefer to write properties file format, and then switch to YAML. I did a multi-data source project before, but I failed to configure it in YAML. At that time, THERE was no hint of multi-data source in IDEA, which really gave me a headache. If you feel this headache, there is an online tool to convert properties into YAML.

@ PropertySource profile

We speak of values above and the assignment are go Spring Boot default configuration files: application. The properties, application, yml. Properties takes precedence over YAML in Spring Boot. But what if there are configuration files that we don’t want to write to the default file and want to pull out and load separately? This is actually done via @propertysource. We can still look at the comments on the source code, just look at the comments on the source code as much as possible.

Annotation providing a convenient and declarative mechanism for adding a @link org.springframework.core.env.PropertySource PropertySource} to Spring’s

{@link org.springframework.core.env.Environment Environment}. To be used in conjunction with @{@link Configuration} classes.

The @propertysource annotation is used in conjunction with Spring’s environment variables on top of the configuration class.

There are examples in the code, so let’s do just that. First we’ll prepare a properties file:

testbean.name=myTestBean
Copy the code

Then prepare the configuration class and a javaBean:

@Getter
@Setter
@NoArgsConstructor
@ToString
public class TestBean {
    private String name;
}

@Configuration
@PropertySource(value = "classpath:app.properties")
public class SpringBootConfig {
    private Environment env;

    @Autowired
    public void setEnv(Environment env) {
        this.env = env;
    }

    @Bean
    public TestBean testBean() {
        TestBean testBean = new TestBean();
        testBean.setName(env.getProperty("testbean.name"));
        return testBean;
    }
}
Copy the code

Test it out:

@RunWith(SpringRunner.class)
@SpringBootTest
class BootApplicationTests {

	@Autowired
	private TestBean bean;

	@Test
	void contextLoads(a) { System.out.println(bean); }}Copy the code

Test results:

@importResource still requires configuration files

Although configuration classes are powerful, some are not portable to configuration classes. There is a comment in @importResource like this:

but where some XML functionality such as namespaces is still necessary. But some XML features such as namespaces are still required. It seems to have something to do with the Groovy language, and since Spring is not just Java, it seems to be a big topic to discuss in terms of Spring as a whole, but let’s just think of the rest as introducing XML configuration files.

How do you use it? Just make a Java Bean in the configuration file and load it on the Spring Boot main class. First we prepare a configuration file:


      
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	<! This is just an example, actually this is more suitable for configuration classes.	
    <bean id = "testBean" class = "com.example.boot.pojo.TestBean">
        <property name="name" value="zd"/>
    </bean>
</beans>
Copy the code

Then introduce on the main class:

@SpringBootApplication
@ImportResource(locations = "classpath:spring-mvc.xml")
public class BootApplication {
    public static void main(String[] args) { SpringApplication.run(BootApplication.class, args); }}Copy the code

Test code:

@RunWith(SpringRunner.class)
@SpringBootTest
class BootApplicationTests {

    @Autowired
    private TestBean bean;
    @Test
    void contextLoads(a) { System.out.println(bean); }}Copy the code

Test results:

Configuration file location

For those of you familiar with Maven, you may know that maven has a convention for a directory structure, resources, which we call the resource folder, where we will put our configuration files. The application. Properties file is loaded by default when Spring Boot starts, and yamL is used if it doesn’t. Properties always take precedence over YAML. However, if both exist at the same time, the conflicting configuration direction is dominated by the configuration of properties. If they do not conflict, they complement each other (as if merged in a configuration file).

If your project is so large that you need to split the configuration files and place them in a separate folder, Spring Boot will look for configuration files here by default:

  • File: project root path /config(config folder is level with resource folder)
  • File: root directory of the project
  • Classpath: resource file location /config
  • Classpath: resource file location/project root directory

Priorities go from top to bottom.

Context switching

We’ve emphasized that we have three sets of configuration files for development (Dev), test (UAT), and production (PROD). How do we make it so that the application uses different configuration files for different environments? Spring Boot thought about that, too. Sweet, sweet. If there is a properties file, the properties file is preferentially selected for reading.

Specify the activation environment in the master profile.

Let’s take properties as an example, yamL is the same, so I don’t show it here. First we create a configuration file in the development environment named application-dev.properties, which specifies the port:

server.port=8885
Copy the code

Then select the active file environment from the main configuration file:

server:
  port: 8882
  servlet:
    context-path: /study
Spring:
  profiles: dev
Copy the code

Note that dev aligns with the configuration files in the development environment through application-environment. When you restart, you will find that the port is 8882.

Operation parameters

The Spring Boot Web application is made into a JAR package, and the java-jar xxx.jar command is used to start a JAR package in Java.

For example, java-jar xxx.jar —-spring.profiles.active=uat, and then spring Boot will load the file named application-uat. In IDEA, we can achieve the corresponding effect:

Then you’ll notice that the run parameters have the highest priority. In the main configuration file we specify dev environment, and in the run parameters we specify UAT environment.

VM arguments

JVM parameters, which we usually use to limit the memory of the JVM because the JVM eats as much memory as it can. General command format Java – parameter. We can also use this to set the boot environment, in the following configuration of IDEA:

The same effect can be achieved.

Ideas for Spring Boot integration

sum

Above we talked about Spring Boot turning the various scenarios we developed into a variety of starter, which we only need to introduce on demand when developing. Once introduced, Spring Boot enables auto-configuration classes to integrate automatically by configuring the necessary file parameters in the configuration file. So here is a summary of the general steps of Spring Boot development:

  • Find a starter based on the scenario

Spring’s official starter dependency name usually starts with spring-boot-starter. You can find it on the official website. If it does not belong to the Spring Boot, the starter is usually spring-boot-starter, such as mybatis-spring-boot-starter

  • Set parameters in the configuration file based on the initiator.

Integration of MyBatis

First let’s think carefully about what MyBatis needs. First of all, we definitely need mybatis-spring-boot-starter, which is done by Mybatis for us, which has integrated some necessary. But let’s see, this launcher shouldn’t integrate:

  • Database connection pool

If this integration is implemented, we will have to pay attention to the trend of connection pools in the market.

  • Database driver

This should also allow developers to choose their own, after all, there are many databases, many driver versions. Starter integrates so much, it’s coupled.

Then we introduce dependencies:

<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 2.1.4 < / version > < / dependency > < the dependency > < the groupId > com. Alibaba < / groupId > < artifactId > druid - spring - the boot - starter < / artifactId > < version > 1.1.22 < / version > </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> The < version > 5.1.47 < / version > < / dependency >Copy the code

Then how to set parameters: We still search baidu to see if there is an official document:Click inside to have a look:There’s an example of that, and here we’re just going to put it together, and it’s important to understand the idea. Druid = Druid = Druid = Druid = Druid = Druid = Druid = Druid = Druid = Druid = Druid Server. port=8884

server.servlet.context-path=/studyBoot mybatis.mapper-locations=classpath*:com/example/boot/mapper/*.xml Spring. The datasource. The druid. Url = JDBC: mysql: / / 192.168.2.129:3306 / study? useUnicode=true&characterEncoding=utf-8 spring.datasource.druid.username=root spring.datasource.druid.password=RrXMoWG8+6gl spring.datasource.druid.driver-class-name=com.mysql.jdbc.DriverCopy the code

Remember that in our SSM integration we have mapper. XML and mapper. XML interfaces.Spring Boot will automatically associate @mapper annotations with the XML specified in mapper-locations. If you want to customize it, you can use @mapperscan, which specifies which packages you want to scan. The specific code, you can go to GitHub.

Integrate Redis

Next, let’s do an exercise to try to integrate Redis in Spring Boot. The first step is to find the starter for Redis:

Let’s click inside and have a look:

Spring Boot has become a starter for Redis, so we should first go to the starter table of Spring Boot. No longer follow the library-spring-boot-starter to baidu to find official documents. The one we found above is a layer of encapsulation on top of Spring, so we will only integrate what Spring provides. We can see that the configuration class of MyBatis is MybatisProperties, so we can also guess by analogy, Redis configuration class is RedisProperties, in fact, I think so when integrating, and then sure enough it is. Let’s match it:

Spring. Redis. Host = 192.168.2.129:6379 spring. Redis. Password = foobaredCopy the code

Then we can configure the RedisTemplate in the Spring configuration class.

To summarize

This article basically introduces the basic use and basic principle of Spring Boot, counting my previous several articles, the whole is basically satisfactory. If you want to learn the framework might as well follow my article, the order is:

  • Welcome to the Spring era – Introduction
  • Welcome to the Spring era
  • Proxy pattern – Introduction to AOP
  • Welcome to the Spring era (ii) AOP
  • Pretend to be a white man
  • Pretend to be white and learn Spring MVC
  • Pretend to be white and learn Spring MVC(2)
  • And then this piece
  • Spring Cloud tutorial for beginners

I hope it will be helpful for everyone to learn.

The resources

  • SpringBoot Video tutorial
  • Software version GA, RC, and Beta