SpringBoot开发组件总结

大家好,今天学习了SpringBoot中间件开发,在学习后总结记录下。

在开发的过程中,把一些公共的非业务的代码提炼出来,做成一个公用的组件,减少开发成本和风险,今天学习的是一个白名单控制组件,记录一下组件开发的过程。

一、编写spring.factory配置自动配置的类

在resource目录的META-INF下的spring.factories中定义

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.wq.whitelist.config.WhiteListAutoConfigure

二、编写自动配置类

自动配置类的作用是读取yml中定义的配置,并将其加入到spring容器中,在配置时一般会加入@ConditionalOnMissingBean防止和其他同名的bean冲突。

/**
 * 只有当WhiteListProperties存在是才会注册WhiteListAutoConfigure到容器中
 */
@Configuration
@ConditionalOnClass(WhiteListProperties.class)
@EnableConfigurationProperties(WhiteListProperties.class)
public class WhiteListAutoConfigure {

    /**
     * 这个地方加上@ConditionalOnMissingBean的目的是防止容器中多个bean冲突而出现异常,一般在自动配置类中加上这个
     * 比如这里我加上这个,在引入我的项目里也有whiteListConfig的bean的时候,就会使用别人的,如果那个项目中没有的话就使用我的。
     */
    @Bean("whiteListConfig")
    @ConditionalOnMissingBean
    public String whiteListConfig(WhiteListProperties properties) {
        return properties.getUsers();
    }

}

三、定义注解

自定义一个注解,在使用的时候在需要的地方加上注解即可。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DoWhiteList {
    String returnJson() default "";
}

四、编写切面逻辑

这一步也是最关键的,主要的逻辑都是在这里实现,通过spring的aop对方法进行拦截,再对其进行判断。

    @Around("aopPoint()")
    public Object doRouter(ProceedingJoinPoint jp) throws Throwable {
        Object target = jp.getArgs()[0];
        Field[] declaredFields = target.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            if ("white".equals(field.getName())) {
                field.setAccessible(true);
                if (field.get(target) != null && (boolean)field.get(target)) {
                    field.setAccessible(false);
                    return jp.proceed();
                }
            }
        }
        // 拦截
        Class<?> returnType = method.getReturnType();
        String returnJson = whiteList.returnJson();
        if ("".equals(returnJson)) {
            return returnType.newInstance();
        }
        return JSON.parseObject(returnJson, returnType);
    }

到这里就开发完成啦,将项目install到仓库中,在需要的项目中引入此项目的依赖即可

五、测试

    @DoWhiteList(returnJson = "{\"code\":\"1111\",\"info\":\"非白名单可访问用户拦截!\"}")
    @RequestMapping(path = "/api/queryUserInfo", method = RequestMethod.POST)
    public UserInfo queryUserInfo(@RequestBody UserInfo userInfo) {
        return userInfo;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值