Introduction to Spring Boot Vue Element: Practical Spring Boot+Mybatis+Redis+Swagger

This blog is originally created by the author. It is forbidden to reprint without permission. Please respect the originality! If you have any questions, please contact QQ509961766.

(1) Modification of POM files

Open the pom file
First add spring boot dependencies to the top text

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.7.RELEASE</version>
</parent>

Then add dependencies to dependencies

<!-- spring-boot-web -->
<dependency>
   <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- mybatis-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.0</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.0</version>
</dependency>
<!-- springboot+mybatis Official Connection Pack -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-autoconfigure</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>
<!-- Paging plugins -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.2</version>
</dependency>
<!-- mysql Database Driver -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- druid Connection pool -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.9</version>
</dependency>
<!-- Swagger -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>
<!-- json -->
<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>
<!-- log-->
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>

(2) Perfecting the properties configuration file

First, open the application.properties file to separate the development test generation environment. It's also convenient to package. Let's take the test environment as an example.

#Development/test/Production environment corresponds to each other dev/test/prod
spring.profiles.active=test

Then create a new application-test.properties file

server.port=8088
server.context-path=/user
logging.config=classpath:logback-spring.xml
#Database Configuration
jdbc.datasource.driver=org.gjt.mm.mysql.Driver
jdbc.datasource.url=jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=utf8&autoReconnect=true
jdbc.datasource.username=root
jdbc.datasource.password=root123
# Here are additional settings for connection pooling that apply to all of the above data sources# Initialization size, minimum, maximum
jdbc.datasource.initialSize=5
jdbc.datasource.minIdle=5
jdbc.datasource.maxActive=20
# Configuration to get the connection waiting timeout time
jdbc.datasource.maxWait=60000
# How often is the configuration interval detected to detect idle connections that need to be closed in milliseconds?
jdbc.datasource.timeBetweenEvictionRunsMillis=60000
# Configure the minimum lifetime of a connection in the pool in milliseconds
jdbc.datasource.minEvictableIdleTimeMillis=300000
jdbc.datasource.validationQuery=SELECT 1 FROM DUAL
jdbc.datasource.testWhileIdle=true
jdbc.datasource.testOnBorrow=false
jdbc.datasource.testOnReturn=false
# Whether to cache preparedStatement, or PSCache. PSCache has greatly improved the performance of database supporting cursors, such as oracle. It is recommended to close under mysql.
jdbc.datasource.poolPreparedStatements=false
# Configure filters intercepted by monitoring statistics and sql can not be counted after removing them.'wall'For defense sql injection
jdbc.datasource.filters=stat,wall,log4j
# Open mergeSql function by connecting Properties attribute;SQLRecord
jdbc.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=2000
# Merging monitoring data from multiple Druid Data Sources
#jdbc.datasource.useGlobalDataSourceStat=true

# Redis database index (default0) 
spring.redis.database=0
# Redis server address
spring.redis.host=127.0.0.1
# Redis Server Connection Port
spring.redis.port=6379
# Redis server connection password (default is empty)
spring.redis.password=wangpan
# Maximum number of connections in connection pool (no restrictions with negative values)
spring.redis.pool.max-active=8
# Maximum blocking waiting time for connection pools (using negative values to indicate no restrictions)
spring.redis.pool.max-wait=-1
# Maximum idle connection in connection pool
spring.redis.pool.max-idle=8
# Minimum idle connection in connection pool
spring.redis.pool.min-idle=0
# Connection timeout time (milliseconds)
spring.redis.timeout=60000

# druid connection pool configuration
stat.servlet=/druid/*
stat.allow=192.168.1.225
stat.deny=192.168.1.73
stat.loginUsername=admin
stat.loginPassword=123456
stat.resetEnable=false
stat.urlPatterns=/*
stat.exclusions=*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*

(3) Improving logback-spring.xml configuration file

Create a new logback-spring.xml file in the resources directory

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- File output format -->
    <property name="PATTERN" value="%-12(%d{yyyy-MM-dd HH:mm:ss.SSS}) |-%-5level [%thread] %c [%L] -| %msg%n"/>

    <!--console output -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${PATTERN}</pattern>
        </encoder>
    </appender>
    <!-- Generate a file every day  INFO -->
    <appender name="INFO-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!-- File path -->
        <file>logs/info/info.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- File name -->
            <fileNamePattern>logs/info/info.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <!-- Maximum number of saved history files -->
            <maxFileSize>100MB</maxFileSize>
            <MaxHistory>50</MaxHistory>
            <totalSizeCap>10GB</totalSizeCap>
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
        </rollingPolicy>

        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${PATTERN}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <!-- One file per day  ERROR -->
    <appender name="ERROR-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!-- File path -->
        <file>logs/error/error.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- File name -->
            <fileNamePattern>logs/error/error.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <!-- Maximum number of saved history files -->
            <maxFileSize>100MB</maxFileSize>
            <MaxHistory>50</MaxHistory>
            <totalSizeCap>10GB</totalSizeCap>
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
        </rollingPolicy>

        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${PATTERN}</pattern>
        </encoder>

        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

	<!--Switch console output or file output here-->
    <logger name="dao" level="debug" additivity="false">
        <appender-ref ref="console"/>
        <!--<appender-ref ref="INFO-FILE" />-->
        <!--<appender-ref ref="ERROR-FILE" />-->
    </logger>
	<!--Switch console output or file output here-->
    <root level="info">
        <appender-ref ref="console"/>
        <!--<appender-ref ref="INFO-FILE" />-->
        <!--<appender-ref ref="ERROR-FILE" />-->
    </root>
</configuration>

(4) Project catalogue

  • common: tool class, encapsulation class
  • config: Configuration class, interceptor
  • Controller: controller
  • dao: data layer
  • mapper: mybatis xml Mapping
  • Entity: database entity class mapping
  • service: Business Layer Interface
  • impl: Business layer implementation class
  • vo: Business layer data object
  • Application: Startup class

Source code generation uses generateCode.exe tools to automatically generate controller,dao,mapper,service,impl,vo,entity and other code, including the most basic add-delete check, paging function.
Later, I will open source this generateCode.exe tool to Git, greatly improve the efficiency of development, one-click automatic generation of add, delete, modify and check functions, database entity class mapping, and so on.

Add data sources, mybatis, swagger, redis, interceptors, etc. to config. See the source code for details.

(5) Start-up works

Modify the Application first, as follows, right-click to start the project

package com.wwhy;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@MapperScan(value = "com.wwhy.dao")
@ServletComponentScan
public class Application{

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

The console prints the following instructions for successful startup
Let's test whether mybatis and swagger are integrated successfully.
Enter http://localhost:8088/user/druid/index.html in the browser with user password: admin/123456

The database connection pool made by Ali can monitor sql.
Then enter http://localhost:8088/user/swagger-ui.html in the browser to display the system interface, indicating success.

Previous article: Spring Boot Vue Element Initial Practical Warfare (11) Backend Spring Boot Service Architecture
Next article: Introduction to Spring Boot Vue Element
Click here to return to the directory

Source code download

Github: 
https://github.com/Iamoldwang/spring-boot-vue.git
Gitee: 
https://gitee.com/Iamoldwang/spring-boot-vue.git

Keywords: Spring JDBC Redis Mybatis

Added by kevo1162 on Tue, 24 Sep 2019 09:44:56 +0300