Spring Boot with Custom Converters breaks Swagger & how to move it - spring-boot

I have a very simple Spring Boot application. I launch this through the basic SpringApplication.run(Startup.class, args); and have a custom #Configuration class in there that overrides the default converters. I decided to add Swagger to the mix of things so that I can generate better documentation for our internal user base as there are gads of endpoints.
When I started things up, Swagger simply wouldn't work.
I decided to start a front-scratch Spring Boot with just one endpoint to document to see what went wrong. Out-of-the box this worked perfectly fine and I was able to get Swagger running via just hitting the http://localhost:8080/swagger-ui.html base URL.
When I implemented my custom #Configuration class that extended WebMvcConfigurationSupport, Swagger no longer worked.
My configuration overrode a single method:
#Configuration
public class StartupConfiguration extends WebMvcConfigurationSupport {
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(getJsonConverter());
}
}
That's it. I decided to add the default converters as well without any luck. Then I just emptied the class and left it as:
#Configuration
public class StartupConfiguration extends WebMvcConfigurationSupport {
}
Swagger is still broken - if I remove the class completely, then it works.
What can I do to keep my custom configuration data and run Swagger? I would also love to move it to something like http://localhost:8080/swagger/ rather than the default file it uses, but that is a completely separate issue for now.
My launch of Swagger looks like this:
#Configuration
#EnableSwagger2
public class SwaggerConfiguration {
#Bean
public Docket getDocket() {
// ...
return new Docket(DocumentationType.SWAGGER_2)
.groupName("Core API")
.apiInfo(infoBuilder.build())
.select().paths(PathSelectors.regex("/*"))
.build();
}
}

Overriding the default resource handler worked for me. I added the following to the configuration class extending WebMvcConfigurationSupport:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry
.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}

Related

Component inside auto configuration application not getting registered

I have created a simple spring boot starter configuration.
Along with other files I have Interceptor which should auto-register.
My Configuration is registered in the file is as follow:
/resource/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports=DynamicDataSourceAutoConfiguration
Autoconfiguration kicks in but the components inside this are not initialized.
My default component inside auto configuration is as follow;
#Component
public class AppWebMvcConfigurer implements WebMvcConfigurer {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CommonHeadersInterceptor());
}
}
This starter I am using in multiple micro-service.
Since it is not registered automatically. I have to re-create this AppWebMvcConfigurer file in each of my micro-services.
Please help me if there is some other configuration I need to do for AutoConfiguration to kick in.
FYI: Other files include
Properties
Configuration
DataSources
EDIT:1
I created config file and added the same path in .imports file metioned above. For time being this seems solved.
#Configuration
public class HeaderTenantMvcConfiguration {
#Bean
public AppWebMvcConfigurer webMvcConfigurer() {
return new AppWebMvcConfigurer();
}
}
My org.springframework.boot.autoconfigure.AutoConfiguration.imports now looks something like this:
com.silentsudo.data.DataSourceAutoConfig
com.silentsudo.web.mvc.AppWebMvcConfigurer

Reason for #EnableWebSecurity in the configuration class

I just read answer from the another question What is the use of #EnableWebSecurity in Spring?, but i couldn't understand why we need to add #EnableWebSecurity annotation at all.
Even I remove the #EnableWebSecurity from the configuration, my application still works.
Let's assume that we are going to implement either JWT based (rest api) or simply login based mvc application. For the following configuration what i am missing?
#Component
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Bean
public UserDetailsService userDetailsService() {
return new MyCustomUserDetailsService();
}
#Bean
public PasswsordEncoder passwsordEncoder() {
return new BrcyptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// for the jwt authentication add jwt filter etc ..
// for the login based, override default login page, error page etc..
}
}
If you are not using spring-boot but just a pure spring project , you definitely need to add #EnableWebSecurity in order to enable spring-security.
But if you are using spring-boot 2.0 +, you do not need to add it by yourself because the spring-boot auto configuration will automatically do it for you if you forget to do so. Under the cover , it is done by the WebSecurityEnablerConfiguration which its javadoc also states this behaviour as follows:
If there is a bean of type WebSecurityConfigurerAdapter, this adds the
#EnableWebSecurity annotation. This will
make sure that the annotation is present with default security
auto-configuration and also if the user adds custom security and
forgets to add the annotation.

Spring boot 2.0 with swagger ui not working properly

I am trying to integrate Spring Boot 2.0 with swagger but not showing up end points.When I looked to developer console on network tab ,it says that I couldn't find "http://localhost:8080/swagger-resources/configuration/ui" and return 404.
We solved this problem by adding resource handler for swagger:
Example:
#Configuration
public class MvcConfiguration extends WebMvcConfigurationSupport {
#Value("${spring.application.name}")
private String applicationName;
//...irrelevant code here
#Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
If you have #EnableWebMvc or #WebMvcConfigurationSupport annotation anywhere in the project then remove these or add custom resource handlers to configure swagger-ui.
Here's some common solutions:
https://github.com/springfox/springfox/issues/2396#issuecomment-402150402

Spring Boot - custom 404 page with standalone tomcat

I am running a Spring boot application inside a standalone tomcat instance, and I am trying to override the error pages. From my understanding, Spring provides a filter ErrorPageFilter that allows me to just setup error pages as normal for Springs EmbeddedServletContainerCustomizer to handle this case exactly.
So I have my standard auto configuration/servlet initializer in one class:
#Configuration
#ComponentScan
#EnableAutoConfiguration(exclude = [ GroovyTemplateAutoConfiguration, SecurityAutoConfiguration, ErrorMvcAutoConfiguration, JmxAutoConfiguration ] )
class Application extends SpringBootServletInitializer {
#Override protected SpringApplicationBuilder configure( SpringApplicationBuilder application ) {
application.sources( Application )
}
(I am using the same class for autoconfiguration and servlet init, which is why i just pass my Application class in the configure method)
Looking at the source code for SpringBootServletInitializer it looks like the ErrorPageFilter class is being added by just extending that class here. I have turned off the ErrorMvcAutoConfiguration - but again, looking at that source code it looks like that is just setting default error pages and not actually setting anything up with the ErrorPageFilter.
I then have my error config file:
#Configuration
class ErrorConfiguration implements EmbeddedServletContainerCustomizer {
#Override public void customize( ConfigurableEmbeddedServletContainer container ) {
container.addErrorPages(new ErrorPage( HttpStatus.NOT_FOUND, "/errors/404" ))
}
However, if I just visit an invalid URL, and I DispatcherServlet can't find a match then I just get tomcats /404.html - not my view linked to "/errors/404" (I have this path mapped to a thymeleaf view template, that works fine - if I navigate to /errors/404 it displays ok)
Any ideas why my custom error page is not working? tracing the logs, I get a line about the ErrorPageFilter being configured and setup ok on application startup, but then no mentions of the filter doing anything when a request comes in.
You can use following code for older versions of spring boot (0.5.x)
public class ServerCustomization extends ServerProperties {
#Override
public void customize(ConfigurableEmbeddedServletContainerFactory factory) {
super.customize(factory);
factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,
"/yourpath/error-not-found.jsp"));
factory.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,
"/yourpath/error-internal.jsp"));
factory.addErrorPages(new ErrorPage("/yourpath/error-other.jsp"));
}
}
Newer spring boot versions (1.X.RELEASE) has some refactoring around ServerProperties. See below,
public class ServerCustomization extends ServerProperties {
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
super.customize(container);
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,
"/jsp/404.jsp"));
container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,
"/jsp/500.jsp"));
container.addErrorPages(new ErrorPage("/jsp/error.jsp"));
}
}
Then define a bean to inject ServerProperies.
#Bean
public ServerProperties getServerProperties() {
return new ServerCustomization();
}
Sample project posted in git
Very Important: If you are using maven to build, You must store all the resource files under src/main/resources folder. Otherwise maven will not add those files to final jar artifact.
You can either use Spring Boot's builtin error view by implementing a view named error, or switch it off by setting error.whitelabel.enabled=false property and implement your own. It's explained more in the docs.

META-INF/resources not works properly with #EnableWebMVC in Spring Boot

1.
I'm working with Spring Boot. My Main class very simple
#ComponentScan
#EnableAutoConfiguration
#Configuration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
#2. Now I would like to make my static content externalised into a jar file. So, below is the jar project
/pom.xml
/src/main/resources/META-INF/resources/hello.json // here is my resource
I do maven install and put the dependency into the main app, run the app normally. Now I can invoke http://localhost:8080/hello.json to get my hello.json file
#3. Then, the next step is using the Apache Tiles for my main web project, so I create a #EnableWebMvc class to configure the tilesViewResolver
#Configuration
#EnableWebMvc
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
public #Bean TilesViewResolver tilesViewResolver() {
return new TilesViewResolver();
}
public #Bean TilesConfigurer tilesConfigurer() {
TilesConfigurer ret = new TilesConfigurer();
ret.setDefinitions(new String[] { "classpath:tiles.xml" });
return ret;
}
}
Then I started again the application and try the hello.json to ensure everything still works properly. But, the 404 page appear. Delete the WebMvcConfiguration give back my hello.json.
What configuration I should do to resolve this issue?
Thanks a lot.
In Spring MVC, using XML configuration, you have to have a tag like the following to service static content:
<mvc:resources mapping="/js/**" location="/js/"/>
This insinuates that Spring Boot is doing something to automatically guess that you have static content and properly setup the above example in META-INF/resources. It's not really "magic", but rather that they have a default Java Configuration using #EnableWebMvc that has some pretty reliable default values.
When you provide your own #EnableWebMvc, my guess is you are over-writting their "default" one. In order to add back a resource handler, you would do something like this:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
}
This is equivalent to the XML above.

Resources