Добавление аннотаций к существующему классу во время выполнения не оказывает никакого влияния - PullRequest
0 голосов
/ 06 февраля 2019

Моя проблема заключается в том, что я добавляю аннотации, более конкретно, аннотацию @Path к классу ресурсов jersey во время выполнения (с использованием javassist), но до запуска сервера и инициализации сервлета jersey, а также я могу убедиться, что аннотация правильно получаетсядобавлен в класс, но когда я пытаюсь вызвать свой веб-сервис, вызвав конечную точку класса ресурса, я получаю ошибку 404, и я не могу понять, что я делаю неправильно.Вот код

 public static void main(String[] args) throws Exception {
            ClassPool pool = ClassPool.getDefault();
            CtClass ccd = pool.get("org.demonking.JettyServiceApp2");
            ClassFile cfile = ccd.getClassFile();
            ConstPool cpool = cfile.getConstPool();
             AnnotationsAttribute attr =
            new AnnotationsAttribute(cpool, AnnotationsAttribute.visibleTag);
            //AnnotationsAttribute attr =  (AnnotationsAttribute) cfile.getAttribute(AnnotationsAttribute.visibleTag);
            Annotation annot = new Annotation(javax.ws.rs.Path.class.getCanonicalName(), cpool);
            annot.addMemberValue("value", new StringMemberValue("/hello2", cpool));
            attr.addAnnotation(annot);
            ccd.getClassFile().addAttribute(attr);
            ccd.toClass(JavassistDemoMain.class.getClass().getClassLoader(),
                    JavassistDemoMain.class.getClass().getProtectionDomain());
            Class.forName("org.demonking.JettyServiceApp2");
            java.lang.annotation.Annotation[] annotations=org.demonking.JettyServiceApp2.class.getAnnotations();
            for(java.lang.annotation.Annotation an:annotations)
            {
                System.out.println("annotated with "+an.annotationType());

            }
            Class<?> cls=org.demonking.JettyServiceApp2.class;

            java.lang.annotation.Annotation[] annotations2=cls.getMethod("test").getAnnotations();
            for(java.lang.annotation.Annotation an:annotations2)
            {
                System.out.println("annotated with "+an.annotationType());

            }
            javax.ws.rs.Path path=org.demonking.JettyServiceApp2.class.getAnnotation(javax.ws.rs.Path.class);
            System.out.println(path.value());
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
            context.setContextPath("/JettyApp");
            ServletHolder holder = new ServletHolder();
            holder.setName("jettyApp");
            holder.setClassName(org.glassfish.jersey.servlet.ServletContainer.class.getName());
            holder.setInitParameter("javax.ws.rs.Application", "org.demonking.AppConfig");
            System.out.println(holder.getInitParameter("javax.ws.rs.Application"));
            holder.setInitOrder(0);
            context.getServletHandler().addServlet(holder);
            ServletMapping mapping = new ServletMapping();
            mapping.setServletName("jettyApp");
            mapping.setPathSpec("/*");
            context.getServletHandler().addServletMapping(mapping);
            Server jettyServer = new Server(9081);
            jettyServer.setHandler(context);
            jettyServer.start();

        }

, а вот мой класс JettyServiceApp2, у которого нет аннотации @Path

public class JettyServiceApp2 {
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Message test() {
        Message msg = new Message();
        msg.id = 101;
        msg.message = "hello this is test message indicating every thing is fine";
        return msg;
    }
}
...