how upgrade swagger2 to swagger3 in plain spring project - spring-mvc

In our spring-webmvc project we are using the following code to configure swagger2, now we want to upgrade to swagger3, so we added springdoc-openapi-ui in pom file, what changes we need to make in our swagger-configuration file
#Configuration
#EnableSwagger2
public class SwaggerConfiguration {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.hjk.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(getApiInfo());
}
private ApiInfo getApiInfo() {
return new ApiInfo(title, description, version, termsOfServiceUrl, contact, license, licenseUrl);
}
}

You have to remove #EnableSwagger2
and change your Docket api() like this.
#Bean
public OpenAPI customOpenAPI() {
return new OpenAPI().info(new Info().title("SpringShop API"));}
For more details Please refer to this docs https://springdoc.org/#migrating-from-springfox.

Related

Thymeleaf View Resolver with SpringMVC webapp

How if one can use ThymeleafViewResolver as a defalt view resolver.
Currentely my WebMvcConfig looks like this
#Configuration
#ComponentScan(basePackages="com.greatLearning.ticketAPI.controller")
public class WebMvcConfig implements WebMvcConfigurer {
#Autowired
ApplicationContext applicationContext;
// #Override
// public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
// configurer.enable();
// }
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
//Thymeleaf ViewResolver
#Bean
public SpringResourceTemplateResolver templateResolver(){
// SpringResourceTemplateResolver automatically integrates with Spring's own
// resource resolution infrastructure, which is highly recommended.
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
// HTML is the default value, added here for the sake of clarity.
templateResolver.setTemplateMode(TemplateMode.HTML);
// Template cache is true by default. Set to false if you want
// templates to be automatically updated when modified.
templateResolver.setCacheable(true);
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine(){
// SpringTemplateEngine automatically applies SpringStandardDialect and
// enables Spring's own MessageSource message resolution mechanisms.
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
// Enabling the SpringEL compiler with Spring 4.2.4 or newer can
// speed up execution in most scenarios, but might be incompatible
// with specific cases when expressions in one template are reused
// across different data types, so this flag is "false" by default
// for safer backwards compatibility.
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
#Bean
public ThymeleafViewResolver viewResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
// NOTE 'order' and 'viewNames' are optional
viewResolver.setOrder(1);
viewResolver.setViewNames(new String[] {".html", ".xhtml"});
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
}
for *.jsp view it is working just fine, but I want to use Thymeleaf to resolve my .html templates becasue I don't want to use *.jsp .
One thing to note is that in my controller
TestController.java
#RequestMapping("/hello")
public String method1() {
return "hello";
}
#RequestMapping("/hello2")
#ResponseBody
public String method2() {
return "hello"; //This works fine
}
when I hit /hello api this is what I get
How do I configre viewResolver so that spring picks up ThymeleafViewResolver to resolve html rather than jsp
Problem Solved!!!!!
Here is what I did after an hour of debugging the libraries
in WebMvcConfig.java I revomed the public InternalResourceViewResolver resolver() method as it is sed to configure jsp.
Now in ThymeleafViewResolver viewResolver() remove these two:
viewResolver.setOrder(1);
viewResolver.setViewNames(new String[] {".html", ".xhtml"});
got help through debgging and [this post](Problem Solved!!!!!
Here is what I did after an hour of debugging the libraries
in WebMvcConfig.java I revomed the public InternalResourceViewResolver resolver() method as it is sed to configure jsp.
Now in ThymeleafViewResolver viewResolver() remove these two:
viewResolver.setOrder(1);
viewResolver.setViewNames(new String[] {".html", ".xhtml"});
got help through debgging and this post.
As to why I will answer if anyone is interested. :)

How do I using RedisMessageListenerContainer in configuration class

I am using spring-MVC and spring-data-redis to control Redis-cluster pool.
When I using jedisCluster.subscribe(new JedisPubSubListener(), "bb");
my application will stock in this code(I try to use thread but the other one can't get the instance in #autowerid).
I google a lot of way point me to using spring-boot .
but I can change the structure in our project.
So I think when spring init I can register a listener to use.
But I can run sauce in my original code.
Can someone make an example for me if I using this following code :
#Configuration
public class RedisClusterConfig {
private List<String> redisNodes(){
return Arrays.asList(redisNode.split(","));
}
#Bean
JedisPoolConfig jedisPoolConfig(){
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(maxTotal);
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMinIdle(minIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
jedisPoolConfig.setTestOnBorrow(testOnBorrow);
jedisPoolConfig.setTestOnReturn(testOnReturn);
jedisPoolConfig.setTestWhileIdle(testWhileIdle);
return jedisPoolConfig;
}
#Bean
RedisConnectionFactory redisClusterConnectionFactory(JedisPoolConfig
jedisPoolConfig){
JedisConnectionFactory redisConnectionFactory = new
JedisConnectionFactory(new RedisClusterConfiguration(redisNodes()));
redisConnectionFactory.setPoolConfig(jedisPoolConfig);
return redisConnectionFactory;
}
}
this is how I setting in my configuration.
#Bean
public RedisMessageListenerContainer redisMessageListenerContainer() {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnectionFactory);
container.addMessageListener(consumerRedis(),topic());
return container;
}
#Bean
public ConsumerRedisListener consumerRedis() {
return new ConsumerRedisListener();//this class implements MessageListener
}
#Bean
public ChannelTopic topic() {
return new ChannelTopic("channel");
}

addResourceHandler #EnableWebMvc setup

My handler was working prior to some dependency updates and ditching of the XML in my app. But now I get this error
org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping for GET /resources/img/logo.png
My view resolver is working fine, my controller is pointing to the right places it is just my css/js that doesn't seem to map.
public class ConfigClass {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
WebMvcConfigurationSupport appears to be essential.
public class ConfigClass extends WebMvcConfigurationSupport{
//Rest here
}
EDIT
The initial answer was based on an amateur "cached" answer. The actual solution was using
public class ConfigClass extends WebMvcConfigurerAdapter {
However, this is now deprecated. Am looking into an answer for that.

Hide/remove Spring MVC endpoint in Swagger2

I'm using Swagger 2 for API UI. So, my gradle.build has:
compile "io.springfox:springfox-swagger2:${swaggerVersion}"
compile "io.springfox:springfox-swagger-ui:${swaggerVersion}"
I've configured Swagger as below:
#Configuration
#Profile("!production")
#EnableSwagger2
#ComponentScan(basePackageClasses = com.company.controllers.ContentController.class)
public class SwaggerConfiguration {
#Autowired
private BuildInfo buildInfo;
#Bean
public Docket awesomeApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(this.awesomeApiInfo())
.select()
.apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
.build();
}
private ApiInfo awesomeApiInfo() {
return new ApiInfoBuilder()
.title("Awesome API - build #" + this.buildInfo.getVersion())
.description("Enter the IDs in order to look for the content")
.version("0.1")
.build();
}
}
I'm getting the api endpoint that I have defined, but also getting the Spring MVC endpoints as below:
Now, I need to get rid of these mvc endpoints.
Any help is highly appreciated!!
Ohhh... actually it was my silly mistake. I changed RequestHandlerSelectors to select only endpoints from my own controller package as follow:
#Bean
public Docket awesomeApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(this.awesomeApiInfo())
.select()
.paths(PathSelectors.any())
.apis(RequestHandlerSelectors.basePackage("com.company.awesome.controllers"))
.build();
}
And this shows only the endpoints mapped within the classes in controller package.
The best approach you can follow is to restrict visibility and access to ServiceStack. So you can hide it from being visible externally with:
[Restrict(VisibleInternalOnly = true)]
public class InternalAdmin { }
you can read more about it here
An alternative to specifying base package is to create a class annotation like this:
#Target({ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Documented
#Component
public #interface SwaggerDocumentation {
}
and then once defined use it on your Controller as desired:
#RestController
#SwaggerDocumentation
public class EntityRestController {
EntityService entityService;
#Autowired
public EntityRestController(final EntityService entityService) {
this.entityService = entityService;
}
#GetMapping("/status")
String getTest() {
return "Ready";
}
#GetMapping("/api/entities")
Collection<Entity> getEntities() {
return entityService.findSome();
}
}
and then finally in the SwaggerConfig class
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(SwaggerDocumentation.class))
.build();
}
}

springfox does not return the api doc

I'm trying to integrate springfox in to my existing sprint web application I configured the springfox the web app is starting correctly but the api doc is not getting generated
here is the springfox configuration class
#EnableSwagger2 //Loads the spring beans required by the framework
public class SwaggerConfig {
#Bean
public Docket swaggerSpringMvcPlugin() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
}
here is the bean creation
<bean id="config" class="com.myApp.general.SwaggerConfig"/>
following is the controller
#Controller
public class MyController {
#ApiOperation(value = "Gets architecture services",
notes = "",
produces = "application/json")
#RequestMapping(value = "v1/users", method = RequestMethod.GET)
#ResponseBody
public Object users(HttpServletResponse response) {
//method implementation
}
}
when i try to get the api doc it just returns a 404. can someone help me on this
it may be a late answer..but should help people still looking/searching
anyway the below answer should work .
for html the ui.html handler is needed
and for others webjars/** is needed
uri.startsWith("/swagger")|| uri.startsWith("/webjars")||uri.startsWith("/v2/api-docs");
if you have filter-chain to access-specific url's ,be sure to omit any filter cheking similar to above code
#Component
public class SwaggerConfiguration extends WebMvcConfigurerAdapter {
#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/");
}....
adding above code makes your spring application to look into the folders for swagger-ui files.
if you already have a resource handler..donot forget to include these there.In this case no need to write a special resource handler

Resources