If you haven’t starting working with spring boot yet, you will quickly find that it pulls out all the common configuration from across your applications. Recently I helped in an effort to modularize configuration and worked on creating a spring-boot-swagger starter project. This project, like other boot modules, would be included in the pom and you would enjoy the fruits of auto configuration.

If you aren't familiar with swagger, swagger is a "specification and complete framework implementation for describing, producing, consuming, and visualizing RESTful web services". It has various integration points with java back end technologies (JAX-RS, scala, php, nodejs, etc) but even better it has separated the front end into a project called swagger-ui. So as long as your service complies to the spec you can have a pretty UI on top of your rest services. It does lack official support spring MVC though there are various projects on github that attempt to integrate the two, even I started a project. Also there has been talk in spring’s JIRA about swagger support.

We went with swagger-springmc simply due to the number of watchers/stars and it fit in pretty good with little effort. It can be integrated with traditional spring XML or through java config both ways requiring two properties to be set to specify the API version and the base path. With the direction of spring-boot, we wanted to abstract the dependency and defaults so consuming apps would just have to plug it in to the pom.xml. It lead us down a few options which we described below and in the end landed on #3 of Injecting ConfigurableApplicationContext in one of our auto configuration classes.

Option 1 - PropertyPlaceholderConfigurer

As martypitt / swagger-springmvc states in the documentation you can configure the properties programmatically with the PropertyPlaceholderConfigurer. We need the properties in spring's Environment class, a class that manages profiles and properties, but PropertyPlaceholderConfigurer is not able to add properties to environment. PropertySourcesPlaceholderConfigurer uses Environment and not vice versa. Also, we wanted this in the spring boot module, not all consuming rest applications. In case this works for you, this is what the configuration would look like:

 @Bean
public static PropertyPlaceholderConfigurer swaggerProperties() throws UnknownHostException { // Swagger expects these to property values to be replaced. We don't want to propagate these to consumers of
// this configuration, so we derive reasonable defaults here and configure the properties programmatically.
Properties properties = new Properties();
properties.setProperty("documentation.services.basePath", servletContext.getContextPath());
// this property will be overridden at runtime, so the value here doesn't matter
properties.setProperty("documentation.services.version", "REPLACE-ME"); PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
configurer.setProperties(properties);
configurer.setIgnoreUnresolvablePlaceholders(true);
return configurer;
}

Option 2 - Implementing ApplicationContextInitializer

ApplicationContextInitializer is a call back interface for initializing ConfigurableApplicationContext prior to being refreshed typically used within web applications that require some programmatic initialization of the application context. So this would work great, on start up we can set the two properties but what it doesn't give us is the ability to get hold of a ServletContext through ServletContextAware because it fires to early on in the spring lifecycle.

So if your application will deploy to a single environment or if you want to require each of your applications to specify the properties required in the application.properties file, this solution might work for you. It would look something like this:

In your spring.factories within your boot starter project you would need to add:

org.springframework.context.ApplicationContextInitializer=com.levelup.SomeInitializer

Then add the following class

public class SwaggerApplicationContextInitializer implements
ApplicationContextInitializer<ConfigurableApplicationContext> { @Override
public void initialize(ConfigurableApplicationContext applicationContext) { MutablePropertySources propertySources = applicationContext
.getEnvironment().getPropertySources(); Map<String, Object> propertyMap = new HashMap<String, Object>();
propertyMap.put("documentation.services.basePath",
"http://localhost:8080/participant");
propertyMap.put("documentation.services.version", "REPLACE-ME"); propertySources.addFirst(new MapPropertySource(
"documentation.services", propertyMap)); }
}

Option 3 - Injecting ConfigurableApplicationContext

At the end of the day this solution may not be spring certified and there probably another way to do it but worked. ConfigurableApplicationContext classprovides facilities to configure an application context in addition to the application context client methods. So we created a class that implements InitializingBean that allows us to react once all their properties have been set. It allows us to configure the properties need and then add them to the environment so when the DocumentationConfig looks for them, they are available.

@Configuration
@AutoConfigureBefore(SwaggerAutoConfiguration.class)
@EnableConfigurationProperties({ SwaggerBeanProperties.class })
public class SwaggerPropertiesAutoConfiguration implements InitializingBean,
ServletContextAware { private ServletContext servletContext; @Autowired
ConfigurableApplicationContext applicationContext; @Autowired
SwaggerBeanProperties swaggerBeanProperties; @Override
public void afterPropertiesSet() throws Exception { MutablePropertySources propertySources = applicationContext
.getEnvironment().getPropertySources(); Map<String, Object> propertyMap = new HashMap<String, Object>();
propertyMap.put("documentation.services.basePath",
getDocumentBasePath()); propertyMap.put("documentation.services.version", getDocumentVersion()); propertySources.addFirst(new MapPropertySource(
"documentation.services", propertyMap)); } private String getDocumentBasePath() { if (swaggerBeanProperties.getBasePath() != null) {
return swaggerBeanProperties.getBasePath();
} else {
return servletContext.getContextPath();
}
} private String getDocumentVersion() { if (swaggerBeanProperties.getVersion() != null) {
return swaggerBeanProperties.getVersion();
} else {
return "1.0";
}
} @Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
}

We all have heard it before, "we don't want the base configuration" so we created a @ConfigurationProperties class that will look for the properties and will be injected into SwaggerPropertiesAutoConfiguration above. If properties are set in the application we will apply them, otherwise we will look for the defaults in hopes to create consistency across all apps.

@AutoConfigureBefore(SwaggerPropertiesAutoConfiguration.class)
@ConfigurationProperties(name = "documentation.services", ignoreUnknownFields = true)
public class SwaggerBeanProperties { private String basePath;
private String version; public String getBasePath() {
return basePath;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}

The last class was simply to import the DocumentationConfig.class

@Configuration
@Import(DocumentationConfig.class)
public class SwaggerAutoConfiguration {
}

Finally, the spring.factories

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
boot.web.swagger.autoconfigure.SwaggerAutoConfiguration,\
boot.web.swagger.autoconfigure.SwaggerPropertiesAutoConfiguration org.springframework.context.ApplicationContextInitializer=

Spring-boot was made to solve the "we have ever which way to configure an application" syndrome but occasionally you still might have get dirty. It might not be perfect but it works for now. If you have suggestions or other ways this could be handled, let me know.

Configure swagger with spring boot posted by Justin Musgrove on 16 April 2014

http://www.leveluplunch.com/blog/2014/04/16/spring-boot-swagger-springmvc-configuration/

Configure swagger with spring boot的更多相关文章

  1. 使用Swagger生成Spring Boot REST客户端(支持Feign)(待实践)

    如果项目上使用了Swagger做RESTful的文档,那么也可以通过Swagger提供的代码生成器生成客户端代码,同时支持Feign客户端. 但是经过测试,生成Feign代码和REST客户端有些臃肿. ...

  2. Swagger Learing - Spring Boot 整合swagger

    学习了一下swagger. 这是编写的Demo 源码 https://github.com/AmberBar/Learning/tree/master/swagger-learning/swagger ...

  3. Spring Boot初识(3)- Spring Boot整合Swagger

    一.本文介绍 如果Web项目是完全前后端分离的话(我认为现在完全前后端分离已经是趋势了)一般前端和后端交互都是通过接口的,对接口入参和出参描述的文档就是Mock文档.随着接口数量的增多和参数的个数增加 ...

  4. Spring Boot 2.x基础教程:Swagger接口分类与各元素排序问题详解

    之前通过Spring Boot 2.x基础教程:使用Swagger2构建强大的API文档一文,我们学习了如何使用Swagger为Spring Boot项目自动生成API文档,有不少用户留言问了关于文档 ...

  5. Spring Boot 集成 Swagger 生成 RESTful API 文档

    原文链接: Spring Boot 集成 Swagger 生成 RESTful API 文档 简介 Swagger 官网是这么描述它的:The Best APIs are Built with Swa ...

  6. Spring Boot实战:集成Swagger2

    一.Swagger简介 上一篇文章中我们介绍了Spring Boot对Restful的支持,这篇文章我们继续讨论这个话题,不过,我们这里不再讨论Restful API如何实现,而是讨论Restful ...

  7. Developing JSF applications with Spring Boot

    Developing JSF applications with Spring Boot Spring Boot can leverage any type of applications, not ...

  8. Spring Boot文档维护:集成Swagger2

    一.Swagger简介 在日常的工作中,我们往往需要给前端(WEB端.IOS.Android)或者第三方提供接口,这个时我们就需要提供一份详细的API说明文档.但维护一份详细的文档可不是一件简单的事情 ...

  9. Spring Boot 入门系列(二十二)使用Swagger2构建 RESTful API文档

    前面介绍了如何Spring Boot 快速打造Restful API 接口,也介绍了如何优雅的实现 Api 版本控制,不清楚的可以看我之前的文章:https://www.cnblogs.com/zha ...

随机推荐

  1. AFNetworking (3.1.0) 源码解析 <六>

    这次继续介绍文件夹Serialization下的类AFURLResponseSerialization.这次介绍就不拆分了,整体来看一下.h和.m文件. 协议AFURLResponseSerializ ...

  2. Core OS 层

    Core OS层的底层功能是很多其他技术的构建基础.通常情况下,这些功能不会直接应用于应用程序,而是应用于其他框架.但是,在直接处理安全事务或和某个外设通讯的时候,则必须要应用到该层的框架. Acce ...

  3. android 时间对话框 TimePickerDialog简介

     个人也提醒功能的时候用到了TimePickerDialog对话框,查阅了非常多技术资料,可是感觉非常多东西都说的不是非常具体,而且非常多地方.都有不完好的地方.比方有弹出对话框得到的不是系统当前 ...

  4. Android自己定义控件之应用程序首页轮播图

    如今基本上大多数的Android应用程序的首页都有轮播图.就是像下图这种(此图为转载的一篇博文中的图.拿来直接用了): 像这种组件我相信大多数的应用程序都会使用到,本文就是自己定义一个这种组件,能够动 ...

  5. EEPlat 的数据层模式

    EEPlat 的数据库底层架构能够同一时候支持多种数据库的集成应用.同一时候能够支持分布式数据库的集成应用.业务对象通过指定数据源与对应的数据库通过数据源层进行数据交互,数据源层通过数据库种类.自己主 ...

  6. iOS:编译错误Undefined symbols for architecture i386: _OBJC_CLASS_$_XXX&quot;, referenced from: error

    Undefined symbols for architecture i386: _OBJC_CLASS_$_XXX", referenced from: error 这个意思为无法找到名为 ...

  7. Java基础知识强化之集合框架笔记03:Collection集合的功能概述

    1. Collection功能概述:Collection是集合的顶层接口,它子体系有重复的,有唯一性,有有序的,无序的. (1)添加功能 boolean add(Object obj):添加一个元素 ...

  8. git 的记住用户名和密码和一些常用

    git config --global core.autocrlf falsegit config --global color.ui truegit config --global credenti ...

  9. HTML之Data URL(转)

    Data URL给了我们一种很巧妙的将图片“嵌入”到HTML中的方法.跟传统的用img标记将服务器上的图片引用到页面中的方式不一样,在Data URL协议中,图片被转换成base64编码的字符串形式, ...

  10. 对SQL Server SQL语句进行优化的10个原则

    1.使用索引来更快地遍历表. 缺省情况下建立的索引是非群集索引,但有时它并不是最佳的.在非群集索引下,数据在物理上随机存放在数据页上.合理的索引设计要建立在对各种查询的分析和预测上.一般来说:①.有大 ...