1.自定义注解

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface PermissionOperation {

    /** * 权限Code * @return */
    String code();

    /** * 权限描述 * @return */
    String description();
}

2.场景

在项目中遇到一个场景,想获取所有注解为@PermissionOperation的code和description值保存到数据中,将所有的权限操作在启动的时候同步到数据库中,在Spring启动的时候获取特定注解@PermissionOperation的所有属性值,首先想到的是写一个监听器然后监听ApplicationListener 事件,具体代码如下:

@Component
public class StartupListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //获取@JalorOperation注解的所有bean
       Map<String,Object> map= ContextHolder.getContext().getBeansWithAnnotation(PermissionOperation.class);
        //循环判断是否存在,获取属性值
    }
}

但是这里是有问题的,因为一旦spring管理的bean中Scope注解为session/request的时候有时候会出现问题。

3.利用BeanPostProcessor接口

@Component
public class MyListenerProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());
        if (methods != null) {
            for (Method method : methods) {
                PermissionOperation permissionOperation = AnnotationUtils.findAnnotation(method, PermissionOperation.class);
                if (null != permissionOperation) {
                    //插入到数据中
                    System.out.println(permissionOperation.code());
                    System.out.println(permissionOperation.description());
                }
            }
        }
        return bean;
    }
}

Spring管理的bean初始化化完成之后执行这个方法,我们就可以在这里进行一系列的逻辑。

4.例子

这里启动之后要获取到code和description值

@RestController
@RequestMapping(value = "access")
public class UserController {

    /** * @param id * @return */
    @GetMapping("add")
    @PermissionOperation(code = "权限Code1", description = "添加用户")
    public int addUser(@RequestParam Integer id) {
        System.out.println("UserController add is running");
        return Integer.MAX_VALUE;
    }

    /** * @param id * @return */
    @DeleteMapping("del")
    @PermissionOperation(code = "权限Code2", description = "删除用户")
    public int delUser(@RequestParam Integer id) {
        System.out.println("UserController delete is running");
        return Integer.MAX_VALUE;
    }
}

可以看到在控制台打印出:

权限Code1
添加用户
权限Code2
删除用户

本文转载自:https://blog.csdn.net/qianyiyiding/article/details/77150864