SpringBoot+Swagger2 配置完成 --Java-Java-E先生的博客
Java
MySQL
大数据
Python
前端
黑科技
大语言模型
    首页 >> 互联网 >> Java

SpringBoot+Swagger2 配置完成 --Java

[导读]:SpringBoot一个原则,爱好编程的朋友们都知道,那就是习惯优于配置。 闲话不多说了,下面贴代码: 一、导入依赖 project xmlns=http://maven.apache.org/POM/4.0.0 xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xs...
  SpringBoot一个原则,爱好编程的朋友们都知道,那就是"习惯优于配置"。
  闲话不多说了,下面贴代码:
  一、导入依赖
  <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.0modelVersion>
  <groupId>cn.bloggroupId>
  <artifactId>blog001artifactId>
  <version>0.0.1-SNAPSHOTversion>
  <packaging>warpackaging>
  <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>1.5.9.RELEASEversion>
    parent>
 
    <repositories>
        
        <repository>
            <id>aliyunid>
            <url>http://maven.aliyun.com/nexus/content/groups/public/url>
        repository>
        
        <repository>
            <id>snapshotsid>
            <url>https://oss.sonatype.org/content/repositories/snapshots/url>
        repository>
    repositories>
 
    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <maven.compiler.source>1.8maven.compiler.source>
        <maven.compiler.target>1.8maven.compiler.target>
        <mybatis-plus-boot-starter.version>2.1.9mybatis-plus-boot-starter.version>
        <mybatisplus.version>2.1.8mybatisplus.version>
        <HikariCP.version>2.4.13HikariCP.version>
        <fastjson.version>1.2.39fastjson.version>
        <druid.version>1.1.0druid.version>
    properties>
 
    <dependencies>
    
        
    <dependency>
        <groupId>org.apache.shirogroupId>
        <artifactId>shiro-coreartifactId>
        <version>1.2.2version>
    dependency>
    
     
        <dependency>
            <groupId>org.apache.shirogroupId>
            <artifactId>shiro-springartifactId>
            <version>1.3.2version>
        dependency>
        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>2.2.2version>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>2.2.2version>
        dependency>
 
        
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>1.7.19version>
        dependency>
    
            
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>${druid.version}version>
        dependency>
    
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-tomcatartifactId>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>org.apache.tomcat.embedgroupId>
            <artifactId>tomcat-embed-jasperartifactId>
            <scope>providedscope>
        dependency>
 
        <dependency>
            <groupId>com.zaxxergroupId>
            <artifactId>HikariCP-java7artifactId>
            <version>${HikariCP.version}version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>${fastjson.version}version>
        dependency>
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>${mybatis-plus-boot-starter.version}version>
            <exclusions>
                <exclusion>
                    <artifactId>tomcat-jdbcartifactId>
                    <groupId>org.apache.tomcatgroupId>
                exclusion>
            exclusions>
        dependency>
        
 
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>com.jayway.restassuredgroupId>
            <artifactId>rest-assuredartifactId>
            <version>2.9.0version>
            <scope>testscope>
        dependency>
 
        
        <dependency>
            <groupId>org.apache.velocitygroupId>
            <artifactId>velocityartifactId>
            <version>1.7version>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.21version>
        dependency>
 
    dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
project>
  二、编写Java代码
package com.blog.springboot;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
@EnableTransactionManagement
@SpringBootApplication
public class Application {
 
    protected final static Logger logger = LoggerFactory.getLogger(Application.class);
 
 
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);
        logger.info("Application is success!");
     
    }
 
}
  MyMetaObjectHandler.java
package com.blog.springboot;
 
import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
 *  注入公共字段自动填充,任选注入方式即可
 */
//@Component
public class MyMetaObjectHandler extends MetaObjectHandler {
 
    protected final static Logger logger = LoggerFactory.getLogger(Application.class);
 
    @Override
    public void insertFill(MetaObject metaObject) {
        logger.info("新增");
    }
 
    @Override
    public void updateFill(MetaObject metaObject) {
        logger.info("更新");
    }
}
  MybatisPlusConfig.java(扫描Mapper文件)
package com.blog.springboot.config;
 
import java.util.ArrayList;
import java.util.List;
 
import com.baomidou.mybatisplus.incrementer.H2KeyGenerator;
import com.baomidou.mybatisplus.incrementer.IKeyGenerator;
import com.baomidou.mybatisplus.mapper.ISqlInjector;
import com.baomidou.mybatisplus.mapper.LogicSqlInjector;
import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.plugins.parser.ISqlParser;
import com.baomidou.mybatisplus.plugins.parser.tenant.TenantHandler;
import com.baomidou.mybatisplus.plugins.parser.tenant.TenantSqlParser;
import com.blog.springboot.MyMetaObjectHandler;
 
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
 
@Configuration
@MapperScan("com.blog.springboot.mapper*")
public class MybatisPlusConfig {
 
    /**
     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }
 
 
    @Bean
    public MetaObjectHandler metaObjectHandler(){
        return new MyMetaObjectHandler();
    }
 
    /**
     * 注入主键生成器
     */
    @Bean
    public IKeyGenerator keyGenerator(){
        return new H2KeyGenerator();
    }
 
    /**
     * 注入sql注入器
     */
    @Bean
    public ISqlInjector sqlInjector(){
        return new LogicSqlInjector();
    }
 
}
 
  Swagger2.java
package com.blog.springboot.config;
 
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
@Configuration
@EnableSwagger2
public class Swagger2 {
         @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.blog.springboot"))
                    .paths(PathSelectors.any())
                    .build();
        }
 
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("博客系统")
                    .description("世界因编程而美好,编程改变世界")
                    .termsOfServiceUrl("http://520.cn")
                    .contact("yy")
                    .version("1.0")
                    .build();
        }
 
}
 
  WebConfig.java
package com.blog.springboot.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
 
 
 
/**
 *

 * WEB 初始化相关配置
 *

 */
@ControllerAdvice
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
 
     @Bean
        public ViewResolver getViewResolver() {
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix("/WEB-INF/view/");
            resolver.setSuffix(".jsp");
            return resolver;
        }
     @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            //将所有/static/** 访问都映射到classpath:/static/ 目录下
            registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        }
}
 
  UserEntity.java
package com.blog.springboot.entity;
 
import java.io.Serializable;
 
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
 
/**
 *

 * 
 *

 *
 * @author youcong123
 * @since 2018-05-19
 */
@TableName("user")
public class UserEntity extends Model {
 
  
 
    /**
     * 用户ID
     */
    @TableId(value = "user_id", type = IdType.AUTO)
    private Integer user_id;
    /**
     * 用户名
     */
    private String username;
    /**
     * 性别
     */
    private Integer sex;
    /**
     * 电话
     */
    private String phone;
    /**
     * 密码
     */
    private String password;
    /**
     * 等级
     */
    private Integer level;
    /**
     * 用户创建时间
     */
    @TableField("create_time")
    private String createTime;
    /**
     * 邮箱
     */
    private String email;
    /**
     * 登录标识
     */
    private Integer logo;
    /**
     * 登录时间
     */
    @TableField("login_time")
    private String loginTime;
 
 
    public Integer getUserId() {
        return user_id;
    }
 
    public void setUserId(Integer user_id) {
        this.user_id = user_id;
    }
 
    public String getUsername() {
        return username;
    }
 
    public void setUsername(String username) {
        this.username = username;
    }
 
    public Integer getSex() {
        return sex;
    }
 
    public void setSex(Integer sex) {
        this.sex = sex;
    }
 
    public String getPhone() {
        return phone;
    }
 
    public void setPhone(String phone) {
        this.phone = phone;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
 
    public Integer getLevel() {
        return level;
    }
 
    public void setLevel(Integer level) {
        this.level = level;
    }
 
    public String getCreateTime() {
        return createTime;
    }
 
    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    public Integer getLogo() {
        return logo;
    }
 
    public void setLogo(Integer logo) {
        this.logo = logo;
    }
 
    public String getLoginTime() {
        return loginTime;
    }
 
    public void setLoginTime(String loginTime) {
        this.loginTime = loginTime;
    }
 
 
 
    @Override
    public String toString() {
        return "User{" +
        "userId=" + user_id +
        ", username=" + username +
        ", sex=" + sex +
        ", phone=" + phone +
        ", password=" + password +
        ", level=" + level +
        ", createTime=" + createTime +
        ", email=" + email +
        ", logo=" + logo +
        ", loginTime=" + loginTime +
        "}";
    }
 
    @Override
    protected Serializable pkVal() {
        // TODO Auto-generated method stub
        return this.user_id;
    }
}
  
  UserDao.java
package com.blog.springboot.mapper;
 
import com.blog.springboot.entity.UserEntity;
import com.baomidou.mybatisplus.mapper.BaseMapper;
 
/**
 *

 *  Mapper 接口
 *

 *
 * @author youcong123
 * @since 2018-05-19
 */
public interface UserDao extends BaseMapper {
 
}
  UserService.java
package com.blog.springboot.service;
 
import com.blog.springboot.entity.UserEntity;
import com.baomidou.mybatisplus.service.IService;
 
/**
 *

 *  服务类
 *

 *
 * @author youcong123
 * @since 2018-05-19
 */
public interface UserService extends IService {
 
}
 
  UserServiceImpl.java
package com.blog.springboot.service.impl;
 
import com.blog.springboot.entity.UserEntity;
import com.blog.springboot.mapper.UserDao;
import com.blog.springboot.service.UserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
 
/**
 *

 *  服务实现类
 *

 *
 * @author youcong123
 * @since 2018-05-19
 */
@Service
public class UserServiceImpl extends ServiceImpl implements UserService {
 
}
  UserController.java
package com.blog.springboot.controller;
 
 
import java.util.List;
import java.util.Map;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.alibaba.fastjson.JSON;
import com.blog.springboot.entity.UserEntity;
import com.blog.springboot.service.UserService;
 
import io.swagger.annotations.ApiOperation;
 
/**
 *

 *  前端控制器
 *

 *
 * @author youcong123
 * @since 2018-05-19
 */
@Controller
@RequestMapping("/user")
public class UserController {
    
    @GetMapping(value="/test")    
    public String index() {
        
        return "index";
        
    }
    
    @Autowired
    private UserService userService;
    @ApiOperation(value="获取用户列表", notes="")
    @GetMapping(value="/list",produces="application/json;charset=utf-8")
    @ResponseBody
    public String list(Map map) {
        List list = userService.selectList(null);
        map.put("list", list);
        return JSON.toJSONString(map);
        
    }
 
}
 
  UserDao.xml
 
   
     
       
       
       
       
       
       
       
       
       
       
   
 
   
        user_id AS userId, username, sex, phone, password, level, create_time AS createTime, email, logo, login_time AS loginTime
   
 
 
  三、编写配置文件
  application.yml
#app
server:
    port: 8080
 
spring:
  devtools:
    restart:
      enabled: false
 
 
  datasource:
    url: jdbc:mysql://localhost:3306/blog?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
    username: root
    password: 1234
    db-name: blog
    filters: log4j,wall,mergeStat1
 
#mybatis
mybatis-plus:
  mapper-locations: classpath:/mapper/*Dao.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.blog.springboot.entity
  global-config:
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 2
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 2
    #驼峰下划线转换
    db-column-underline: true
    #刷新mapper 调试神器
    refresh-mapper: true
    #数据库大写下划线转换
    #capital-mode: true
 
    #逻辑删除配置(下面3个配置)
    logic-delete-value: 0
    logic-not-delete-value: 1
    #自定义sql注入器,不在推荐使用此方式进行配置,请使用自定义bean注入
    sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
    #自定义填充策略接口实现,不在推荐使用此方式进行配置,请使用自定义bean注入
    meta-object-handler: com.blog.springboot.MyMetaObjectHandler
    #自定义SQL注入器
    #sql-injector: com.baomidou.springboot.xxx
    # SQL 解析缓存,开启后多租户 @SqlParser 注解生效
    sql-parser-cache: true
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
#logging
logging:
  level: warn
 
  四、添加swagger-ui相关界面
 
  swagger-ui界面可以去github下载,地址为:https://github.com/swagger-api/swagger-ui
  我个人下载的是如上红色标记处,最新版
  下载完毕后将其解压,并在dist目录的所有文件放置在static文件夹下的swagger-ui文件夹下
  五、启动Application,访问

 
  swagger界面

本文来自E先生的博客,如若转载,请注明出处:https://javajz.cn

留言区

联系人:
手   机:
内   容:
验证码:

历史留言

欢迎加Easy的QQ