首页 > 解决方案 > 获取所有@PreAuthorize 列表在春天

问题描述

我试图找出一种方法来从弹簧容器中获取所有预授权注释的列表

假设我有类似下面的东西。

    @PreAuthorize("hasPermission(null, 'opetussuunnitelma', 'LUONTI1')")
@PreAuthorize("hasPermission(null, 'opetussuunnitelma', 'LUONTI2')")
@PreAuthorize("hasPermission(null, 'opetussuunnitelma', 'LUONTI3')")

> I need to get that string(hasPermission(null, 'opetussuunnitelma',
> 'LUONTI2')) or at least List<Map> (x=null,y='opetussuunnitelma',
> z='LUONTI1')

有什么办法可以做到这一点,因为我有 n 个这样的注释,我需要解析所有这些注释字符串并用它做一些事情。

标签: springspring-bootspring-mvcspring-securityspring-aop

解决方案


为了在 JVM 中加载所有应用程序的类,您可以尝试使用反射库从 Spring应用程序上下文中获取加载的 bean 或手动将它们添加到静态列表中。也就是说,没有明确和适当的方法可以实现这一目标。

要获取注释,请使用 Java 反射。

更多信息:https ://www.geeksforgeeks.org/method-class-getannotation-method-in-java/

public void handleAnnotations(Class c) {
    try { 
        Method[] methods = c.getMethods(); 

        for (Method method : methods) { 
            PreAuthorize[] annotations = c.getAnnotationsByType(PreAuthorize.class);
            // handle annotations
        } 

    } 
    catch (Exception e) { 
        // handle exception
    } 
}

推荐阅读