在运行时阅读装饰有特定注释的所有类

Gir*_*rma 1 java reflection annotations cdi

我需要在运行时阅读所有装饰有特定注释(例如@HttpSecurity)的类(接口)。扫描后,我希望阅读和解析装饰有注释的类的字段(枚举字段)。例如。

@HttpSecurity
public interface MyHttpSecurityConfig {

public enum secure {
    @Path(pathGroup = "/*", pathName = "")
    @Authc
    @Form(errorPage = "/error.html", loginPage = "/login.html", restoreOriginalRequest = "")
    @Authz
    @AllowedRoles(roles = { "roleA", "roleB" })
    @AllowedGroups(groups = { "groupA" })
    @AllowedRealms(realms = { "realmA" })
    @Expressions(expressions = { "#{identity.isLoggedIn()}" })
    Admin
  }
}
Run Code Online (Sandbox Code Playgroud)

可能存在一个或多个用@HttpSecurity装饰的类/接口。我的第一个要求是获取所有此类,第二个要求是通过读取注释及其在枚举字段上修饰的值来构建HttpSecurityBuilder。第二个要求很好,可以使用反射消除。但是,我的问题是第一个要求。我想用JavaSE核心实现第一个要求,即不使用任何外部依赖项,例如google Reflections。如有必要,可以假定我们具有要在其中扫描类的程序包名称。这是我做过什么用CDI

小智 5

您可以创建一个CDI扩展,以观察来自CDI注释的扫描并创建您的自定义,如下例所示:

1)您需要使用@HttpSecurity 创建一个Qualifier

@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface HttpSecurity {}
Run Code Online (Sandbox Code Playgroud)

2)您需要通过实现接口javax.enterprise.inject.spi.Extension创建扩展:

    package net.mperon.cdi.extension;

    public class MyExtension implements Extension {

    private static final Logger log = LoggerFactory.getLogger(MyExtension.class);

    public <T> void processAnnotatedType(@Observes ProcessAnnotatedType<T> pat) {
        AnnotatedType<T> at = pat.getAnnotatedType();

        //if dont have you anotation, just continue
        if(!at.isAnnotationPresent(HttpSecurity.class)) {
            return;
        }

        //here you can read all annotation from object and do whatever you want:
        log.info("class: {}", at.getJavaClass());
        log.info("constructors: {}", at.getConstructors());
        log.info("fields: {}", at.getFields());
        log.info("methods: {}", at.getMethods());

        //and so more...

    }
Run Code Online (Sandbox Code Playgroud)

}

3)您可以在此处查看所有方法和属性

4)最后,您需要在META-INF / services下创建一个名为javax.enterprise.inject.spi.Extension的服务文件。

5)在此文本文件中,您需要输入扩展名全类名,例如:

net.mperon.cdi.extension.MyExtension
Run Code Online (Sandbox Code Playgroud)