SpringBoot2集成Swagger2方法

本文详细介绍如何在SpringBoot项目中集成Swagger2,包括添加Maven依赖、配置swagger-api.yml文件、实现Swagger2Config类以及解决PropertySource无法解析yml/yaml文件的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 增加pom依赖。
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>${swagger2.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>${swagger2.version}</version>
    </dependency>
  • 配置swagger-api.yml
    swagger:
        api:
          title: 服务名称
          description: 服务描述
          termsOfServiceUrl:
          contact: dytsj@qq.com
          version: V1.0
          groupName: 查询服务API
          basePath: com.power.query
  • 配置文件Swagger2Config 
    @Configuration
    @EnableSwagger2
    public class Swagger2Config {
    
        @Autowired
        private Swagger2Properties swagger2Properties;
    
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .groupName(swagger2Properties.getGroupName())
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage(swagger2Properties.getBasePath()))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        private ApiInfo apiInfo() {
            String[] contactAry=null;
            if(null != swagger2Properties.getContact()){
                contactAry = swagger2Properties.getContact().split("#");
            }
            int contactLength=0;
            if(0 != contactAry.length){
                 contactLength = contactAry.length;
            }
            String contact_name = "";
            String contact_url = "";
            String contact_email = "";
            switch (contactLength) {
                case 1 : contact_name = contactAry[0];
                case 2 : contact_url = contactAry[1];
                case 3 : contact_email = contactAry[2];break;
                default: contact_name = swagger2Properties.getContact();break;
            }
            return new ApiInfoBuilder()
                    .title(swagger2Properties.getTitle())
                    .description(swagger2Properties.getDescription())
                    .termsOfServiceUrl(swagger2Properties.getTermsOfServiceUrl())
                    .contact(new Contact(contact_name,contact_url,contact_email))
                    .version(swagger2Properties.getVersion())
                    .build();
        }
    }
  • Swagger2Properties
    @Component
    @PropertySource(value="classpath:swagger-api.yml",factory = CompositePropertySourceFactory.class)
    @ConfigurationProperties(prefix = "swagger.api")
    public class Swagger2Properties {
    
        private String title;
        private String description;
        private String termsOfServiceUrl;
        private String contact;
        private String version;
        private String basePath;
        private String groupName;
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    
        public String getTermsOfServiceUrl() {
            return termsOfServiceUrl;
        }
    
        public void setTermsOfServiceUrl(String termsOfServiceUrl) {
            this.termsOfServiceUrl = termsOfServiceUrl;
        }
    
        public String getContact() {
            return contact;
        }
    
        public void setContact(String contact) {
            this.contact = contact;
        }
    
        public String getVersion() {
            return version;
        }
    
        public void setVersion(String version) {
            this.version = version;
        }
    
        public String getBasePath() {
            return basePath;
        }
    
        public void setBasePath(String basePath) {
            this.basePath = basePath;
        }
    
        public String getGroupName() {
            return groupName;
        }
    
        public void setGroupName(String groupName) {
            this.groupName = groupName;
        }
    }
  • @PropertySource不能解析yml和yaml文件的问题
public class CompositePropertySourceFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource)
            throws IOException {
        String sourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
        if (!resource.getResource().exists()) {
            // return an empty Properties
            return new PropertiesPropertySource(sourceName, new Properties());
        } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
            Properties propertiesFromYaml = loadYaml(resource);
            return new PropertiesPropertySource(sourceName, propertiesFromYaml);
        } else {
            return super.createPropertySource(name, resource);
        }
    }
    /**
     * load yaml file to properties
     *
     * @param resource
     * @return
     * @throws IOException
     */
    private Properties loadYaml(EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值