- 依赖的引入
- application.yml配置
- Druid配置类
- swagger配置类
- controller,dao,server的创建
- swagger的使用
springboot的构建
通过idea的spring initializer创建(有些没有的依赖,比如Druid和swagger需要手动引入)
这个比较简单可以参考我另一个帖子:https://blog.csdn.net/a3311743/article/details/86499504
maven库地址:https://mvnrepository.com/
最后生成的pom.xml文件如下:
注意:因为jar包版本不同,有可能会不兼容,下面的配置是可以运行的,如果是通过上述的maven库找寻的最新版本,请自行百度对应的配置版本。
<?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 http://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.1.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wsh</groupId>
<artifactId>springboot-framework</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-framework</name>
<description>springboot框架</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--mybatis依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--mybatis依赖包-->
<!--Druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.14</version>
</dependency>
<!--Druid连接池-->
<!--swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!--swagger -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml配置
##不使用Druid连接池的mybatis配置
#spring:
# datasource:
# url: jdbc:mysql://123.207.16.60:3306/springboot-framework
# username: xxx
# password: xxx
##这里的driver根据mysql-connector-java的版本来决定,不同版本的名称不一样
##com.mysql.jdbc.Driver 是 mysql-connector-java 5中的,
##com.mysql.cj.jdbc.Driver 是 mysql-connector-java 6+的
##driver-class-name: com.mysql.cj.jdbc.Driver
##不使用Druid连接池的mybatis配置
##使用Druid连接池的mybatis配置
#设置端口号
server:
port: 8080
#运行的配置版本
spring:
profiles:
active: dev
druid:
allow: #允许登陆的IP地址,设置为本地地址的时候,外网就无法访问
ip: 127.0.0.1
login: #登陆的账户密码
user_name: root
password: root
#用连续三个连字号(---)区分多个文件
---
spring:
profiles: dev
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://123.207.16.60:3306/springboot-framework
username: xxx
password: xxxxxx
type: com.alibaba.druid.pool.DruidDataSource
# 连接池的配置信息
# 初始化大小,最小等待连接数量,最大等待连接数量,最大连接数
initialSize: 1
minIdle: 1
maxIdle: 5
maxActive: 200
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: true
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: false
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j2
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
jpa:
show-sql: true
注意:新版本的Druid(我用的1.1.14),filters中的log4j要改成log4j2,否则会报下面的错误
Druid配置类
package com.wsh.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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 org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig {
private static final Logger log = LoggerFactory.getLogger(DruidConfig.class);
//读取yml里面的配置
@Value("${druid.login.user_name}")
private String userName;
@Value("${druid.login.password}")
private String password;
@Value("${druid.allow.ip}")
private String allowIp;
/**配置数据源,不然无法获取到sql监控,与sql防火墙监控*/
@Bean(name = "default_databaseSource")
@ConfigurationProperties(prefix="spring.datasource")
public DataSource druidDataSource() {
return new DruidDataSource();
}
/**注册druidServlet到spring里,可以看做是druid的配置*/
@Bean
public ServletRegistrationBean druidServlet() {
log.info("init Druid Servlet Configuration ");
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
servletRegistrationBean.setServlet(new StatViewServlet());
servletRegistrationBean.addUrlMappings("/druid/*");
Map<String, String> initParameters = new HashMap<>();
initParameters.put("loginUsername", userName);// 用户名
initParameters.put("loginPassword", password);// 密码
initParameters.put("resetEnable", "false");// 禁用HTML页面上的“Reset All”功能
//initParameters.put("allow", allowIp); // IP白名单 (没有配置或者为空,则允许所有访问)
//initParameters.put("deny", "");// IP黑名单 (存在共同时,deny优先于allow)
servletRegistrationBean.setInitParameters(initParameters);
return servletRegistrationBean;
}
//注册filterRegistrationBean到spring里,这是过滤器
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new WebStatFilter());
//过滤所有请求
filterRegistrationBean.addUrlPatterns("/*");
//不需要过滤的文件
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}
swagger配置类
package com.wsh.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableSwagger2
@Configuration
public class SwaggerConfig {
//是否开启swagger,正式环境一般是需要关闭的,可根据springboot的多环境配置进行设置
@Value(value = "${swagger.enabled}")
Boolean swaggerEnabled;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
// 是否开启
.enable(swaggerEnabled).select()
// 扫描的路径包
.apis(RequestHandlerSelectors.basePackage("com.wsh.controller"))
// 指定路径处理PathSelectors.any()代表所有的路径
.paths(PathSelectors.any()).build().pathMapping("/");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBoo-framework框架")
.description("wsh开发")
// 作者信息
.contact(new Contact("wsh", "https://blog.csdn.net/a3311743/article/details/88765691", "734780180@qq.com"))
.version("1.0.0")
.build();
}
}
application.properties
swagger.enabled=true
controller,dao,server的创建
这个比较简单,可以参考我的另一个帖子:https://blog.csdn.net/a3311743/article/details/86499504
HelloController.java
package com.wsh.controller;
import com.wsh.entity.User;
import com.wsh.service.HelloService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@RestController
@RequestMapping("/hello")
//@RequestMapping(value = "/hello", produces = APPLICATION_JSON_VALUE) //配置返回值 application/json
@Api(tags="用户API")
public class HelloController {
@Autowired
HelloService helloService;
//没用swagger
// @RequestMapping("/getHello")
//用swagger
@PostMapping("/getHello")
@ApiOperation(value = "用户查询", notes = "通过id获取用户名称")
@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用户id", required = true,dataType = "int"),
@ApiImplicitParam(name = "name",value = "用户name",required = false,dataType = "String")})
public String hello(int id,String name){
return helloService.getNameById(id);
}
@PostMapping("/getUser")
@ApiOperation(value = "用户查询", notes = "通过id获取用户全部信息")
@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用户id", required = true,dataType = "int"),
@ApiImplicitParam(name = "name",value = "用户name",required = false,dataType = "String")})
public User getUser(@RequestParam(value = "id")int id, String name){
User user =new User();
user.setAge("10");
user.setName("王思浩");
user.setId(111);
return user;
}
}
HelloService.java
package com.wsh.service;
public interface HelloService {
public String getNameById(int id);
}
HelloServiceimp.java
package com.wsh.serviceimp;
import com.wsh.mapper.UserMapper;
import com.wsh.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class HelloServiceimp implements HelloService {
@Autowired
UserMapper userMapper;
@Override
public String getNameById(int id) {
return userMapper.getNameById(id);
}
}
UserMapper.java
package com.wsh.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("select name from user where id =#{id}")
String getNameById(@Param("id") int id);
}
User.java
package com.wsh.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Component;
@ApiModel(value="user对象",description="用户对象user")
public class User {
@ApiModelProperty(value="用户id")
private int id;
@ApiModelProperty(value="用户名称")
private String name;
@ApiModelProperty(value="用户年龄",hidden=true)
private String age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
SpringbootFrameworkApplication.java
package com.wsh;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.wsh.entity")
public class SpringbootFrameworkApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootFrameworkApplication.class, args);
}
}
完成并测试
访问:http://localhost:8080/druid/login.html
填写登录账号密码(在application.yml配置),然后就能看到具体的连接信息
访问:http://localhost:8080/swagger-ui.html
就能看到接口的相关信息,还能在线测试接口