Configure Swagger with spring boot

Source: Internet
Author: User

If you haven ' t starting working with spring boot yet, you'll 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 is project, like other boot modules, would is included in the Pom and you would enjoy the fruits of auto configuration.

If you aren ' t familiar with swagger, swagger are a "specification and complete framework implementation for describing, Producing, consuming, and visualizing RESTful Web services. It had various integration points with Java back end technologies (Jax-rs, Scala, PHP, Nodejs, etc) but even better it had Separated the front end into a project called swagger-ui. So as long as your service complies to the spec can has a pretty UI on top of your rest services. It does lack official support spring MVC though there is various projects on GitHub this attempt to integrate the and EV En i started a project. Also There have 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 the properties to being set to SP Ecify 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 has to Plug it in to the pom.xml. It leads us down a few options which we described below and in the end landed on #3 of injecting Configurableapplicationcon Text in one of our auto configuration classes.

Option 1-propertyplaceholderconfigurer

As MARTYPITT/SWAGGER-SPRINGMVC states in the documentation can configure the properties programmatically with the Pr Opertyplaceholderconfigurer. We need the properties in spring's environment class, a class that manages profiles and properties, but Propertyplaceholde Rconfigurer is not able to the add properties to environment. Propertysourcesplaceholderconfigurer uses environment and not vice versa. Also, we wanted this on the Spring boot module, not all consuming rest applications. In the case of this works for you, the "what the" would look like:

 @BeanPublicStaticPropertyplaceholderconfigurerSwaggerproperties()ThrowsUnknownhostexception{Swagger expects these to is replaced. We don ' t want to propagate these to consumers ofThis configuration, so we derive reasonable defaults here and configure the properties programmatically.PropertiesProperties=NewProperties();Properties.SetProperty("Documentation.services.basePath",ServletContext.Getcontextpath());This property is overridden at runtime and so the value is here doesn ' t matterproperties. ( "documentation.services.version"  " Replace-me "propertyplaceholderconfigurer configurer = new span class= "n" >propertyplaceholderconfigurer (); configurer. (propertiesconfigurer. (truereturn configurer;}       
Option 2-implementing Applicationcontextinitializer

Applicationcontextinitializer is a call back interface for initializing Configurableapplicationcontext prior to being REFR Eshed 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 "the" and "what it doesn ' t give us are the ability to get hold of a servletcontext through servletcontextaware because it fires to early on in the spring lifecycle.

So if your application would deploy to a single environment or if you want to require each of the 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 your would need to add:

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

Then add the following class

PublicClassSwaggerapplicationcontextinitializerImplementsApplicationcontextinitializer<Configurableapplicationcontext>{@OverridePublicvoidInitialize(ConfigurableapplicationcontextApplicationContext){MutablepropertysourcesPropertysources=ApplicationContext.Getenvironment().Getpropertysources();Map<String,Object>PropertyMap=NewHashMap<Stringobject> (); propertymap. ( "Documentation.services.basePath" propertymap. ( "documentation.services.version"  " Replace-me "propertysources. (new mappropertysource ( "Documentation.services" propertymap}             /span>                 
Option 3-injecting Configurableapplicationcontext

At the end of the "the day" This solution is not being spring certified and there probably another the "to do it" but worked. Configurableapplicationcontext classprovides Facilities To configure a application context in addition to the application Context client methods. So we created a class that implements Initializingbean this allows us to react once all their properties has been set. It allows us to configure the properties need and then add them to the environment so when the Documentationconfig looks f Or them, they is available.

@Configuration@AutoConfigureBefore(Swaggerautoconfiguration.Class)@EnableConfigurationProperties({Swaggerbeanproperties.Class})PublicClassSwaggerpropertiesautoconfigurationImplementsInitializingbean,Servletcontextaware{PrivateServletContextServletContext;@AutowiredConfigurableapplicationcontextApplicationContext;@AutowiredSwaggerbeanpropertiesSwaggerbeanproperties;@OverridePublicvoidAfterpropertiesset()ThrowsException{MutablepropertysourcesPropertysources=ApplicationContext.Getenvironment().Getpropertysources();Map<String,Object>PropertyMap=NewHashMap<String,Object> ();PropertyMap.Put("Documentation.services.basePath",Getdocumentbasepath());PropertyMap.Put("Documentation.services.version",Getdocumentversion());Propertysources.AddFirst(NewMappropertysource("Documentation.services",PropertyMap));}PrivateStringGetdocumentbasepath(){If(Swaggerbeanproperties.Getbasepath()!=Null){ReturnSwaggerbeanproperties.Getbasepath();}Else{ReturnServletContext.Getcontextpath();}}PrivateStringGetdocumentversion(){If(Swaggerbeanproperties.GetVersion()!= null) {return swaggerbeanproperties. ();  else {return  "1.0" } }  @Override public void setservletcontext (servletcontext servletcontext ) {this. ServletContext = servletcontext}             /span>                

We have heard it before, "we don t want the base configuration" so we created a @ConfigurationProperties class that WI ll look for the properties and would is injected into swaggerpropertiesautoconfiguration above. If Properties is set in the application we'll apply them, otherwise we'll look for the defaults in hopes to create Co Nsistency across all apps.

@AutoConfigureBefore(Swaggerpropertiesautoconfiguration.Class)@ConfigurationProperties(Name="Documentation.services",Ignoreunknownfields=True)PublicClassSwaggerbeanproperties{PrivateStringBasePath;PrivateStringVersion;PublicStringGetbasepath(){ReturnBasePath;}PublicvoidSetbasepath(string basepath) {this basepath = basepath} public string getversion () Span class= "o" >{return version} public void setversion (string version) {thisversion = version}             /span>                

The last class is simply to import the Documentationconfig.class

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

Finally, the Spring.factories

# Auto Configureorg.springframework.boot.autoconfigure.EnableAutoConfiguration=boot.web.swagger.autoconfigure.SwaggerAutoConfiguration,boot.web.swagger.autoconfigure.SwaggerPropertiesAutoConfigurationorg.springframework.context.ApplicationContextInitializer=

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

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

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

Configure Swagger with spring boot

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.