从零搭建 Spring Boot 后端项目(五)

简介

这一小节主要是,整合Swagger2

步骤
  • 在pom.xml下添加如下依赖

    		<!-- swagger2 -->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.7.0</version>
            </dependency>
    
            <!-- swagger-ui -->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.7.0</version>
            </dependency>
    
  • com.example.backend_template.config下新建Swagger2Config类

    package com.example.backend_template.config;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    /**
     * @ClassName Swagger2Config swagger的配置内容即是创建一个Docket实例
     * @Description 
     * @Author L
     * @Date Create by 2020/6/30
     */
    @Configuration
    @EnableSwagger2 //启用swagger2
    public class Swagger2Config {
    
        //是否开启 swagger-ui 功能,默认为false
        @Value("${swagger.enable:false}")
        private Boolean enable;
    
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .enable(enable)
                    .pathMapping("/")
                    .apiInfo(apiInfo())
                    .select()
                    //需要Swagger描述的接口包路径,如果不想某接口暴露,可在接口上加@ApiIgnore注解
                    .apis(RequestHandlerSelectors.basePackage("com.example.backend_template.controller"))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        //配置在线文档的基本信息
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("BackendTemplate项目")
                    .description("使基于SpringBoot的后端开发变得简单")
                    .version("1.0")
                    .build();
        }
    }
    
  • application-dev.properties中添加如下配置

    # Swagger
    # 是否启用Swagger
    swagger.enable=true
    
  • 使用 swagger 注解

    • @Api注解可以用来描述当前Controller的功能
    • @ApiOperation注解用来描述Controller的方法的作用
    • @ApiResponses 用在Controller的方法上,说明Response集
    • @ApiResponse 用在@ApiResponses里边
    • @ApiImplicitParam注解用来描述一个参数,可以配置参数的中文含义,也可以给参数设置默认值,这样在接口测试的时候可以避免手动输入
    • 如果有多个参数,则需要使用多个@ApiImplicitParam注解来描述,多个@ApiImplicitParam注解需要放在一个@ApiImplicitParams注解中
    • @ApiModel 描述实体对象或响应对象的意义,用在pojo类上
    • @ApiModelProperty 用在实体对象或响应对象的字段上,描述其属性

    使用以上注解,并简单修改下原RedisController类,修改后的内容如下:

    package com.example.backend_template.controller;
    
    import com.example.backend_template.service.RedisService;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiImplicitParam;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.web.bind.annotation.*;
    
    import javax.annotation.Resource;
    
    /**
     * @ClassName RedisController
     * @Description 
     * @Author L
     * @Date Create by 2020/6/26
     */
    @Api(tags = "redis简单测试接口")
    @RestController
    @RequestMapping("redis")
    public class RedisController {
    
        @Resource
        private RedisService redisService;
    
        @ApiOperation("向redis中存储`name`值")
        @ApiImplicitParam(name = "name",value = "名称值",defaultValue = "L",required = true)
        @PostMapping("/setRedis")
        public Boolean setRedis(@RequestBody String name) {
            return redisService.set("name", name);
        }
    
        @ApiOperation("向redis中取`name`值")
        @GetMapping("/getRedis")
        public String getRedis() {
            return redisService.get("name");
        }
    }
    
  • 此时我们因为在项目中已整合了 Spring Security ,那么如果不做额外配置,Swagger2文档路径就会被拦截,此时只需要在Spring Security的配置类SecurityConfig.java中重写父类configure(WebSecurity web)方法,就不会被Spring Security拦截了,修改security/SecurityConfig类为如下代码:

package com.example.backend_template.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.DigestUtils;

/**
 * @ClassName SecurityConfig
 * @Description
 * @Author L
 * @Date Create by 2020/6/30
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsServiceImpl userService;
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        //校验用户
        auth.userDetailsService(userService).passwordEncoder(new PasswordEncoder() {
            //对密码进行加密
            @Override
            public String encode(CharSequence charSequence) {
                return DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
            }
            //对密码进行判断匹配
            @Override
            public boolean matches(CharSequence charSequence, String s) {
                String encode = DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
                boolean res = s.equals(encode);
                return res;
            }
        });
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/index", "/login", "/login-error", "/401").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login").failureUrl("/login-error")
                .and()
                .exceptionHandling().accessDeniedPage("/401");
        http.logout().logoutSuccessUrl("/");
    }

    //使Spring Security不拦截swagger相关文档,以下路径不会经过过滤链
    @Override
    public void configure(WebSecurity web) throws Exception {
        //放行swagger
        web.ignoring().antMatchers(
                "/v2/api-docs",
                "/swagger-resources",
                "/swagger-resources/**",
                "/configuration/ui",
                "/configuration/security",
                "/swagger-ui.html/**",
                "/webjars/**");
        //如启用以下配置,则放行所有路径,方便开发使用,但权限管理时需注释
        //web.ignoring().antMatchers("/**");
    }
}
测试
  • 启动backen_template项目,并访问 http://localhost:8080/swagger-ui.html ,出现以下内容即为swagger的主页面
    在这里插入图片描述
  • swagger 还支持接口测试,接下来简单操作下,点击/redis/getRedis并点击Try it out!按钮
    在这里插入图片描述
    但我们并没有得到值,只得到了如下网页
    在这里插入图片描述
    为什么呢,因为 Spring Security 把/redis/getRedis也拦截了,故我们整合Spring Security后,方便开发可暂时在SecurityConfig类中的configure(WebSecurity web)方法中添加如下代码,但权限开发时一定要记得注释,要不然会影响权限开发
            //如启用以下配置,则放行所有路径,方便开发使用,但权限管理时需注释
            web.ignoring().antMatchers("/**");
    
  • 添加好后,重新启动,再点击/redis/getRedis并点击Try it out!按钮,即可获得该值(当然,你要先存,才能取)
    在这里插入图片描述
  • 接下来试一下/redis/setRedis
    在这里插入图片描述
  • 结果成功如下
    在这里插入图片描述
项目地址

项目介绍:从零搭建 Spring Boot 后端项目
代码地址:https://github.com/xiaoxiamo/backend-template

下一篇

六、统一请求结果格式

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小夏陌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值