一,新建 springboot 工程
springboot 工程的创建方式有好几种,可以在官网提供的工程创建页面进行创建、也可以在 eclipse 中下载插件创建 springboot 工程、或者是在创建了 Maven 工程以后将 springboot 工程依赖的 jar 包引入。当然,做 springboot 工程比较好用的还有 IDEA 等等,总之,对于工程的创建可以选择自己比较常用的方式来创建工程,这里不再赘述。
二,Maven 工程依赖配置
我们使用 eclipse IDE 创建的 springboot 工程目录结构如下面所示。
接下来,配置好 Maven 工程所需要的依赖 jar 包,打开 pom.xml 文件添加依赖。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-restdocs.version>2.0.2.RELEASE</spring-restdocs.version>
<com.alibaba.druid>1.1.10</com.alibaba.druid>
<swagger.version>2.9.2</swagger.version>
<mybatis-plus.version>3.0.2</mybatis-plus.version>
<shiro.version>1.3.2</shiro.version>
</properties>
<dependencies>
<!--SpringBoot Web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--SpringBoot Mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<!--Mybatis plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!--Mybatis 分页插件-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!--分页辅助配置-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.6</version>
</dependency>
<!--MYSQL数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--配置数据连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${com.alibaba.druid}</version>
</dependency>
<!--json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--sl4j-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<!--Shiro 权限框架-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
</dependency>
<!--shiro-web依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${shiro.version}</version>
</dependency>
<!--shiro-spring 支持-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
<!-- shiro 缓存 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.4.0</version>
</dependency>
<!--Swagger配置、支持在线接口文档-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--Swagger UI 配置-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- Mybatis 逆向工程 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- SpringBoot Maven 插件 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- Mybatis 逆向工程 Maven 插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<configuration>
<configurationFile>src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build>
</project>
三,工程配置
在 springboot 的工程中,项目相关部分的配置基本上在 application.yml 文件中都可以完成配置。
server:
port: 9001
servlet:
context-path: /
tomcat:
uri-encoding: UTF-8
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: ${jdbc.url}
username: ${jdbc.username}
password: ${jdbc.password}
type: com.alibaba.druid.pool.DruidDataSource # 配置当前需要使用的数据源的操作类型
filters: stat
initialSize: 2
maxActive: 300
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: false
maxPoolPreparedStatementPerConnectionSize: 200
dbcp2:
min-idle: 5 # 数据库连接池的最小维持连接数
initial-size: 5 # 初始化提供的连接数
max-total: 20 # 最大的连接数
max-wait-millis: 60000 # 等待连接获取的最大超时时间
mvc:
view:
suffix: .html # 配置视图解析
thymeleaf:
cache: false # 开发时设置关闭缓存、可以看到实时效果,注意在系统部署时开启缓存
mybatis-plus:
mapper-locations: classpath*:mybatis/mapper/*.xml
typeAliasesPackage: com.example.demo.entity
jdbc.url: jdbc:mysql://192.168.26.10:3306/demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=UTC&allowMultiQueries=true
jdbc.username: sysc
jdbc.password: sysc
logging:
level.root: debug
file: /demo/demo.log
四,编写自定义配置类
自定义配置相关的部分实现一般是通过 @Configuration 的注解接口配置加上自定义实现的方法来完成的,在这个工程中使用了三处。一是对数据库监控的配置,二是对 Mybatis 分页等的配置,三是对 Swagger 接口的配置,下面分别来看这三个部分的配置类是如何编写的。
DruidConfig.java 数据库监控配置
package com.example.demo.configuration;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
/**
*
* @Title: DruidConfig
* @Description: 数据库监控配置
* @author: 老王说编程
* @date 2021年2月13日 上午11:00:13
*/
@Configuration
public class DruidConfig {
@Bean
public ServletRegistrationBean<StatViewServlet> druidServlet() {
/**
* @Description: 主要实现web监控的配置处理
* @Param: []
* @return: org.springframework.boot.web.servlet.ServletRegistrationBean
* @Author: 老王说编程
* @Date: 2021年2月13日
*/
//表示进行druid监控的配置处理操作
ServletRegistrationBean<StatViewServlet> servletRegistrationBean = new ServletRegistrationBean<StatViewServlet>(
new StatViewServlet(), "/druid/*");
//设置访问IP白名单
servletRegistrationBean.addInitParameter("allow", "");
//设置访问IP黑名单
servletRegistrationBean.addInitParameter("deny", "");
//设置用户名
servletRegistrationBean.addInitParameter("loginUsername", "root");
//设置密码
servletRegistrationBean.addInitParameter("loginPassword", "root");
//不允许重置数据源
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean<WebStatFilter> filterRegistrationBean(){
/**
* @Description: 监控请求、对请求进行过滤
* @Param: []
* @return: org.springframework.boot.web.servlet.FilterRegistrationBean
* @Author: 老王说编程
* @Date: 2021年2月13日
*/
FilterRegistrationBean<WebStatFilter> filterRegistrationBean=new FilterRegistrationBean<WebStatFilter>();
filterRegistrationBean.setFilter(new WebStatFilter());
// 设置请求监控
filterRegistrationBean.addUrlPatterns("/*");
// 允许格式请求
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*");
return filterRegistrationBean;
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource() {
return new DruidDataSource();
}
}
MybatisPlusConfig.java MybatisPlus 分页配置
package com.example.demo.configuration;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.github.pagehelper.PageHelper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
*
* @Title: MybatisPlusConfig
* @Description: Mybatis Plus 分页配置
* @author: 老王说编程
* @date 2021年2月13日 上午11:14:41
*/
@Configuration
@MapperScan("com.example.demo.mapper")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor page = new PaginationInterceptor();
page.setDialectType("mysql");
return page;
}
@Bean
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor page = new PerformanceInterceptor();
page.setFormat(true);
return page;
}
//配置mybatis的分页插件pageHelper
@Bean
public PageHelper pageHelper(){
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("offsetAsPageNum","true");
properties.setProperty("rowBoundsWithCount","true");
properties.setProperty("reasonable","true");
properties.setProperty("dialect","mysql"); //配置mysql数据库的方言
pageHelper.setProperties(properties);
return pageHelper;
}
}
SwaggerConfig.java SwaggerUI 接口配置
package com.example.demo.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
/**
*
* @Title: SwaggerConfig
* @Description: Swagger 在线接口工具配置
* @author: 老王说编程
* @date 2021年2月13日 上午11:03:18
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
List<Parameter> pars = new ArrayList<Parameter>();
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(pars)
.apiInfo(apiInfo());
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("Demo RESTful API")
.description("业务描述")
.termsOfServiceUrl("")
.version("1.0")
.build();
}
}
五,项目结构
使用 DemoApplication.java 启动项目后,访问数据库监控的地址:http://localhost:9001/druid/login.html,swagger 在线接口文档访问地址:http://localhost:9001/swagger-ui.html。