SpringBoot开发组件总结-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

大家好今天学习了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;
    }
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring