mercredi 14 août 2019

Java class.getAnnotation doesn't return external annotation

Java class.getAnnotation doesn't return Annotation on tomcat

i was created two maven modules which application and core

application module use core module's annotation

application module

com.aaa.was.application

public class Application {
    public static void main(String[] args) {
        WasApplication.run(Application.class, args);
    }
}

com.aaa.was.application.controller.TestController

@Controller("hello")
public class TestController {

    public String test() {
        return "test";
    }
}


core module

com.aaa.was.core.WasApplication

 String webappDirLocation = "webapp/";
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8080);

        tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
        logger.info("configuring app with basedir: {}", new File("./" + webappDirLocation).getAbsolutePath());

        tomcat.start();
        tomcat.getServer().await();

com.aaa.was.core.wab.annotations.Controller

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Controller {
    String value() default "asd";
}

com.aaa.was.core.mvc.DispatcherServlet

@WebServlet(name = "dispatcher", urlPatterns = {"/*"}, loadOnStartup = 1)
public class DispatcherServlet extends HttpServlet {
    @Override
    public void init() {
        try {
            run();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
    public void run() throws ClassNotFoundException, IllegalAccessException, InstantiationException {

        String basePackage = "com.aaa.was.application";

        Reflections reflections = new Reflections(basePackage);

        Set<Class<?>> controllers = getTypesAnnotatedWith(reflections, Controller.class);
        for (Class<?> controller : controllers) {
            Controller controllerAnnotation = controller.getAnnotation(Controller.class);
            System.out.println(controllerAnnotation.value());
        }
    }
    public Set<Class<?>> getTypesAnnotatedWith(Reflections reflections, Class<? extends Annotation>... annotations) {
        Set<Class<?>> beanList = Sets.newHashSet();
        for (Class<? extends Annotation> annotation : annotations) {
            beanList.addAll(reflections.getTypesAnnotatedWith(annotation));
        }
        return beanList;
    }
}


error on com.aaa.was.core.mvc.DispatcherServlet class run method System.out.println(controllerAnnotation.value());

controllerAnnotation is null





Aucun commentaire:

Enregistrer un commentaire