In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is to share with you about the process of Springboot integration Swagger2 and common configuration, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
This kind of integrated article is really bad. On the one hand, it is a supplement to my springboot series, on the other hand, there are still some friends who have not used it. Most importantly, if you forget this integrated code. It can be checked at any time.
Preface
Today's development is basically front-end separation, front-end interaction is through API documents. With API documents, we develop their own, do not interfere with each other.
1. Traditional way
The traditional way is that after the document is designed, it is sent to the front-end and back-end personnel respectively. There is a disadvantage that once the interface information changes, the document needs to be re-sent to the front and back end. Can't do it in real time. So waste time and energy.
2. Swagger mode
After our background application integrates swagger, our interface will be automatically exposed, and this interface form is released in restful style. Once there is a change in the back-end interface, it will be immediately displayed, thus greatly improving the efficiency.
OK, basically can sum up its benefits in one sentence, that is, the api documents written at the back end can be published in real time in the form of swagger for front-end staff to view.
3. Other ways
To be honest, the swagger page is not good-looking, and there are some other solutions, either with a lot of bug or for a fee. Swagger is currently the most widely used. I am currently working on this kind of open source project, making pages similar to other schemes based on swagger, and the function is more powerful.
I. Code Integration
The prerequisite is to create a new springboot project. This point will not be demonstrated.
Step 1: add dependencies
Io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2
Version 2.9.2 is the most widely used, you can go directly to the official website of maven to search for a version that is most widely used.
Step 2: configure
Create a new config package and create a SwaggerConfig class
@ EnableSwagger2 @ Configuration public class Swagger2Config {@ Bean public Docket createRestApi () {return new Docket (DocumentationType.SWAGGER_2) .apiInfo (apiInfo ()) .select () / is the current package path Controller class package .apis (RequestHandlerSelectors.basePackage ("com.fdd.controller")) .controller (PathSelectors.any ()) .build () } / / build the details function of the api document private ApiInfo apiInfo () {return new ApiInfoBuilder () / / Page title ("XX platform API Interface document") / / founder .contact (new Contact ("Feng Dongdong", "http://www.javachat.cc",") "3049352171@qq.com")) / / version ("1.0") / / description .description ("system API description") .build () }
The configuration here is also relatively simple. There are many options for us to configure. If our project has multiple groups, we only need to create multiple Docket. At this time, the scanned packet is replaced with the packet path of each group.
Step 3: configure in the controller class
Create a new controller package, and then create a HelloController class
@ Api ("Hello control class") @ RestController public class HelloController {@ GetMapping (value = "/ user") public User getUser () {return new User ("Yu Gong wants to move mountains", "123456");} @ ApiOperation ("API of parameters can be specified") @ PostMapping ("/ param") public String hello2 (@ ApiParam ("username") String name) {return "hello" + name;}}
Here we can see that annotations can be used to explain this class, method, field, and so on. There are many other fields. There will be corresponding prompts when you use them. You can try them yourself:
Step 4: check the results
Visit: http://127.0.0.1:8080/swagger-ui.html.
OK, it's basically integrated at this point. Let's talk about the configurations you might encounter.
III. Other common problems
1. Spring Security-configure authentication-free access
Sometimes our Springboot integrates with SpringSecurity, so if we visit the address of swagger, it will automatically jump to the login page. This is because SpringSecurity intercepted it. To do this, we just need to configure our SpringSecurity to release it.
Now configure it and release it. Create a new SpringSecurityConfig class under the config package
@ Configuration @ EnableWebSecurity public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {@ Override protected void configure (HttpSecurity http) throws Exception {http .authorizeReque sts () .antMatrices ("/ swagger-ui.html"). PermitAll () .antMatrices ("/ webjars/**"). PermitAll () .antMatrices ("/ authorizeReque"). PermitAll () .antMatrices ("/ v2ax *"). PermitAll () .antMatrices ("/ csrf"). PermitAll () .antMatrices ("/"). PermitAll () .anyRequest (). Authenticated () .and () .formLogin () }}
At this point, you can access it normally.
2. Set jwt for swagger
This method is relatively simple and only takes one step. Just modify our swaggerConfig class.
@ EnableSwagger2 @ Configuration public class Swagger2Config {@ Bean public Docket api () {return new Docket (DocumentationType.SWAGGER_2) .apiInfo (apiInfo ()) .securityConcepts (Arrays.asList (securityContext () .securityschemes (Arrays.asList (apiKey () .select () .apis (RequestHandlerSelectors .any () .build () (PathSelectors.any ()) } / / build the details function of the api document private ApiInfo apiInfo () {return new ApiInfoBuilder () / / Page title ("XX platform API Interface document") / / founder .contact (new Contact ("Feng Dongdong", "http://www.javachat.cc",") "3049352171@qq.com")) / / version ("1.0") / / description .description ("system API description") .build () } private ApiKey apiKey () {return new ApiKey ("JWT", "Authorization", "header");} private SecurityContext securityContext () {return SecurityContext.builder (). SecurityReferences (defaultAuth ()). Build ();} private List defaultAuth () {AuthorizationScope authorizationScope = new AuthorizationScope ("global", "accessEverything"); AuthorizationScope [] authorizationScopes = new AuthorizationScope [1] AuthorizationScopes [0] = authorizationScope; return Arrays.asList (new SecurityReference ("JWT", authorizationScopes);}}
Add some token verification code, relatively simple, about JWT things, you can understand in private. I'm not going to repeat it here.
3. Hide Endpoint
Sometimes we can hide the controller written by ourselves, or the interface methods in controller that we don't want the front-end staff to see.
First: hide the entire controller
@ ApiIgnore @ RestController public class MyController {/ / method}
Second: hide an interface method 1
@ ApiIgnore @ ApiOperation (value = "description information") @ GetMapping ("/ getAuthor") public String getAuthor () {return "Yu Gong wants to move mountains";}
Third: hide an interface method 2
@ ApiOperation (value = "description information", hidden = true) @ GetMapping ("/ get") public LocalDate getDate () {return LocalDate.now ();}
OK, many configurations are basically done here.
The above is the process of Springboot integrating Swagger2 and common configuration. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.