Spring Boot 2.3.1.RELEASE 引入 Swagger2


最近在回顾SpringBoot的小知识,其实有些技术什么的早在之前就已经学过并且用过了,就是因为没有做好总结,又加上版本什么的更新的比较快,当我再次去看的时候发现很是生疏啊,所以一定要养成一个做笔记的好习惯。
废话太多,上代码

1.首先引入Maven配置

版本使用SpringBoot2.3.1和swagger的2.9.1的相关版本

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.1</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.1</version>
</dependency>

SpringBoot配置在创建springBoot项目的时候自动引入,这里不贴出来了。

2.添加Swagger2的配置类SwaggerConfig
@Configuration
//@EnableSwagger2WebFlux
//@EnableSwagger2WebMvc
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())//调用apiInfo方法,创建一个ApiInfo实例,里面是展示在文档页面信息内容
                .enable(true)//开启swagger
                .select()
                //控制暴露出去的路径下的实例
                //如果某个接口不想暴露,可以使用以下注解
                //@ApiIgnore 这样,该接口就不会暴露在 swagger2 的页面下
                    .apis(RequestHandlerSelectors.basePackage("com.study.controller"))
//                .apis(RequestHandlerSelectors.withClassAnnotation(ApiOperation.class))//使用注解扫描失败
                .paths(PathSelectors.any())
                .build();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        registry.addResourceHandler("/**")
//                .addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }

    //构建 api文档的详细信息函数
    private ApiInfo apiInfo() {
        Contact contact = new Contact("lidong","localhost:8080","12312312321");
        return new ApiInfoBuilder()
                //页面标题
                .title("测试Swagger2")
                //条款地址
                .termsOfServiceUrl("www.baidu.com")
                .contact(contact)
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }
}

这里又三个注解说明下:
@EnableSwagger2,@EnableSwagger2WebMvc,@EnableSwagger2WebFlux

@EnableSwagger2:是在2.9.1版本以及之前使用这个注解,在2.9.1以后就删除了这个注解。
@EnableSwagger2WebMvc和@EnableSwagger2WebFlux是在2.9.1以后的版本中使用。
这里使用2.9.1版本是因为我在使用2.10.0 的使用出现了问题,所以才降版本的,后续说问题。

别的就都是Swagger2的一些配置了。这里贴两个自己配置的例子,具体含义,网上也都有。

@Api(tags = {"用户相关接口"})
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "user")
    @ApiOperation(value = "根据id获取用户",notes = "这是notes",httpMethod = "POST")
    @ApiImplicitParams(value = {@ApiImplicitParam(name = "id",value = "用户ID",dataType="int",required = true),
    @ApiImplicitParam(name = "username",value = "用户名",dataTypeClass = String.class,required = true),
    @ApiImplicitParam(name = "test",value = "测试参数",dataTypeClass = String.class,required = true)})
    public UserInfo select(int id, String username){
        System.out.println(id+","+username);
        User user = userService.selectUser(id);
        return new UserInfo();
    }

    @RequestMapping(value = "insert")
    public String insert(){

        userService.insert();
        return "success";
    }
package com.study.vo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel("返回参数")
public class UserInfo {
//    @ApiModelProperty(value = "ID",dataType = "int")
//    private Integer id;
    @ApiModelProperty(value = "用户名",notes = "asdasdasd")
    private String username;
    @ApiModelProperty(value = "密码",name = "asdasdasdasd",dataType = "string")
    private String password;

//    public Integer getId() {
//        return id;
//    }
//
//    public void setId(Integer id) {
//        this.id = id;
//    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

然后,启动,访问 http://localhost:8090/swagger-ui.html#/
在这里插入图片描述
出现上面信息,完事。

3.遇到的问题

说下遇到的问题吧
第一个,也是最让我头疼的。最开始我Swagger2版本使用的是2.10.0。配置完成后启动发现访问不了,一直弹窗。
在这里插入图片描述
Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually:

然后我就我从网上找很多办法,设置拦截器啊,配置包扫描路径啊,搞了很长时间都都搞不好。我承认我很懒,这个版本我是实在弄不好。然后我就把版本降到了2.9.1。降了版本之后发现可以访问了。

第二个:降了版本以后又出现了一个问题,页面是能正常出来了,但是没有接口文档。出现了 No operations defined in spec!。
在这里插入图片描述
打开控制台:发现了个错 csrf 404.
在这里插入图片描述
但是我看着地址端口路径什么的应该是没问题的,然后我就想着是不是没有扫描到我的配置,检查代码发现,在去尝试解决上面的问题的时候在启动类上手加了扫描地址。
在这里插入图片描述
因为SpringBoot启动类一般都是放在自己写的类的上层,那样就默认都会扫描到所有写的类,我指定了扫描路径之后就只扫描这个包下面的类了,没有扫描到我配置的controller。所以就没有接口了。
然后去掉这个,再次启动,接口出来了,可以正常测试了。打开控制台发现这两个404错误还存在。。。。。,因为Swagger2不止是像我这个简单的配置一下就行了,它还有很多别的配置,例如权限什么的。所以我猜想应该是Swagger2的另外一些配置没有配所以导致的这个错误。
我这配置的仅仅只是简单的能让我使用就行了,所以对于一些错误也没有去深究。。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'deptServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'deptMapper' defined in file [D:\WorkSpace\work13\djd_server\target\classes\com\jiading\djd\mapper\DeptMapper.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 40; 元素内容必须由格式正确的字符数据或标记组成。 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:893) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879) ~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE] at com.jiading.djd.DjdApplication.main(DjdApplication.java:14) [classes/:na]报错了
07-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值