springboot+自定义注解实现功能增强

需求

原各个业务模块有对应的批量导入、批量修改、批量导出功能,但是批量操作属于大量耗费系统资源的操作,并且没有统一的流程,不便于管理,于是考虑将其加入到定时任务中,上传文件时只是创建任务信息,在系统空闲时进行文件解析、验证、入库操作。
由于定时任务需要根据任务去调用不同模块的文件处理细节并记录处理结果,考虑使用动态代理的方式,将文件解析、数据入库等业务细节分发到具体业务模块,定时任务只负责调用业务处理方法及记录处理结果。
流程:

  1. 自定义注解标记业务处理方法
  2. 依赖springboot扫描功能,将注解标记的方法加载到内存中
  3. 定时任务执行时,使用反射调用具体方法

开始

一、自定义注解

  1. 准备准备知识
    1.1. 元注解
    元注解是由java提供的,所有java中的注解都依赖于元注解。有如下四个注解:
  • @Target: 描述注解的使用范围,可多选
public enum ElementType {
    TYPE, // 类、接口、枚举类
    FIELD, // 成员变量(包括:枚举常量)
    METHOD, // 成员方法
    PARAMETER, // 方法参数
    CONSTRUCTOR, // 构造方法
    LOCAL_VARIABLE, // 局部变量
    ANNOTATION_TYPE, // 注解类
    PACKAGE, // 可用于修饰:包
    TYPE_PARAMETER, // 类型参数,JDK 1.8 新增
    TYPE_USE // 使用类型的任何地方,JDK 1.8 新增
}

使用示例:

// 该注解可标记在方法和类上
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface SysTaskExecuteMethod {}
  • @Retention: 描述注解保留的时间范围
public enum RetentionPolicy {
    SOURCE,    // 源文件保留:仅在源文件中保留,编译时将被忽略
    CLASS,       // 编译期保留(默认值):编译阶段保留,运行期不可见
    RUNTIME   // 运行期保留,可通过反射去获取注解信息
}
  • @Documented: 描述在使用 javadoc 工具为类生成帮助文档时是否要保留其注解信息
  • @Inherited: 描述使被它修饰的注解具有继承性:被他修饰的类,其子类自动继承该注解
    1.2. 创建自定义注解
    创建自定义注解时,使用 @interface标识注解类即可
public @interface CustomerAnnotation {
    // coding
}
  1. 定义注解
    2.1. 定义类标识注解
    因为使用的是springboot的自动扫描及装配实现实例的注册及持有,springboot提供的API只能扫描到类级注解,故此处需要定义一个类注解参与,该注解仅仅作为标记该类有参与细节处理
package com.customer.common.annotation;

import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ClassAnnotation{
}

2.2. 定义业务处理注解
因为使用反射调用具体的方法,所以使用范围为ElementType.METHOD、保留时间为RetentionPolicy.RUNTIME
为了便于区分标识的方法对应的任务分类增加了注解参数

package com.customer.common.annotation;

import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DongingSomething {
    /**
     * 任务名称 
     */
    String taskName();// 不加detault的参数表示为必填参数

    /**
     * 任务所属分类 
     */
    String type();
}

二、注解扫描

使用springboot提供的API实现自定义注解扫描:增加自定义配置,实现org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor接口

@Configuration // springboot启动时会自动识别其为配置项
public class CustomAnnotationScanner implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(beanDefinitionRegistry);
        scanner.setBeanNameGenerator(new AnnotationBeanNameGenerator());
        // 定义需要扫描的注解 -- 自定义注解
        scanner.addIncludeFilter(new AnnotationTypeFilter(ClassAnnotation.class));
        // 定义扫描的包 若不在该包及其子包中,将无法被扫描到
        scanner.scan("com.customer");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
    }

    // 使用springboot上下文获取注解实例,并添加到上下文中,后期使用直接注入即可使用
    @Bean("customerExecuteInstance")
    public List<CustomerExecuteInstance> getAllCustomerExecuteInstance(ApplicationContext applicationContext) {
        List<CustomerExecuteInstance> result = new ArrayList<>();
        // 使用springboot上下文方式获取注解标识的实例
        // springbootAPI未提供直接扫描方法上的注解,故自定义注解有两个,此处使用的是类上的注解
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(ClassAnnotation.class);
        for (Map.Entry<String, Object> item : beansWithAnnotation.entrySet()) {
            // 一般方式使用此方法即可得到方法的注解,比如单元测试中能正常获取到
            Method[] methods = item.getValue().getClass().getMethods();
            // 运行环境下,方法是在service实现类中的,中上下文中的实例其实都是被代理的,此时将无法通过此方法得到方法上的注解
            // 处理被代理的类
            if (AopUtils.isJdkDynamicProxy(item.getValue())){
                Object singletonTarget = AopProxyUtils.getSingletonTarget(item.getValue());
                if (singletonTarget != null) {
                    methods = singletonTarget.getClass().getMethods();
                }
            } else if (AopUtils.isCglibProxy(item.getValue())) {
                methods = item.getValue().getClass().getSuperclass().getMethods();
            }
            for (Method method : methods) {
                SysTaskExecuteMethod annotation = method.getAnnotation(DongingSomething.class);
                if (annotation != null) {
                    // 检查方法返回值 只能是CustomerResult及其子类
                    // 因为需要做后置处理,且后置处理依赖业务处理结果,故此处增加返回参数验证
                    if (!CustomerResult.class.isAssignableFrom(method.getReturnType())) {
                        log.error("\n\t\t*******************" + item.getValue().getClass().getName() + "." + method.getName() + "方法返回值类型不符合规范!*************************");
                        continue;
                    }
                    result.add(
                            new CustomerExecuteInstance()
                                    .setTaskName(annotation.taskName())
                                    .setTaskType(annotation.type())
                                    .setMethod(method)
                                    .setInstance(item.getValue()));
                }
            }
        }

        return result;
    }
}

CustomerExecuteInstance类

@Data // 使用lombok自动增加getter、setter方法
@Accessors(chain = true)// getter、setter方法返回当前对象,方便使用链式编程
public class CustomerExecuteInstance {
    private String taskName;
    private String taskType;
    private Method method;
    private Object instance;

    public boolean equals(String name, String type) {
        if (name == null || type == null) {
            return false;
        }
        return name.equals(this.taskName) && type.equals(this.taskType);
    }
}

三、注解使用

在需要的类及方法上添加注解
示例:

  1. 使用在service类中
@Service // service实现类标识
@ClassAnnotation
public class ModelDoingServiceImpl implements ModelDoingService {

    // Method[] methods = item.getValue().getClass().getMethods()将无法扫描到该注解
    @DongingSomething(taskName = "name1", type = "type1")
    public CustomerResult importMeterInfos(TaskInfo task) {
        // coding.....
       return null;
    }
}
  1. 使用在普通类中
@ClassAnnotation
class A1{

     // Method[] methods = item.getValue().getClass().getMethods()可扫描到该注解
    @DongingSomething(taskName = "test1", type = "type1")
    public CustomerResult testxxx(Long projectId, String fileBusinessId, JSONObject paramsJson) {
        System.out.println("execute method:"+projectId + fileBusinessId+ paramsJson);
        return "execute success";
    }
}

四、定时任务中调用细节处理

定时任务中使用如下:

@Slf4j // 使用日志框架,方便日志输出
public class TaskExecution {
    @Resource // 直接注入bean,springboot上下文中已有他们的实例及相关信息
    private List<CustomerExecuteInstance> executeInstanceList;

    public void executeTask() {
        //查询待执行任务
        List<Task> taskList = new ArrayList();
        // 查询任务类表
        for (Task task : taskList) {
            CustomerExecuteInstance currInst = executeInstanceList.stream()
                    // 使用实体类型中的自定义equles方法
                    .filter(ins -> ins.equals(task.getName(), task.getType()))
                    .findFirst()
                    .orElse(null);
            if (currInst == null) {
                log.warn(task.getType() + " 类型下的【" + task.getName() + "】任务无对应任务执行逻辑。");
                continue;
            }

            try {
                CustomerResult result;
                // 使用反射,直接调用方法处理对应逻辑
                // 此处需要提前约定方法参数只能为 Task及其子类的对象,也可根据需求自行拓展
                result = (CustomerResult) currInst.getMethod().invoke(currInst.getInstance(), task);
                // 记录执行结果
                // doing...
            } catch (Exception e) {
                // 记录执行失败结果
                // doing ...
            }
            // 任务执行结束后的后续操作
            // doing...
        }
    }
}

定时任务如何实现。。。。
这个问题请关注后期补充上 [手动狗头]

五、写在最后

至此,整个业务贯穿打通,实现了业务的分离解耦

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容