0

I have a servlet that I cannot change (com.sun.jersey.spi.container.servlet.ServletContainer of Jersey RS) . What I can do is create a subclass of it. However, I needed that when the servlet is initialized it runs one function of my subclass. I cannot override the init method because it has the Jersey code.

I tried to use the annotation @PostConstruct on a method to make it run after initialization but it does not work (but it does work under Tomcat 6). In web.xml the class is set to run on startup.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Miguel Ribeiro
  • 8,057
  • 20
  • 51
  • 74
  • Why can't you override `init`? The method isn't `final`, so what's the problem? – skaffman May 16 '12 at 10:27
  • I ain't no Java expert, but I would need to copy the whole code from the existing source code to mine right? And also, the init(WebConfig webconfig) access a private attribute webComponent. – Miguel Ribeiro May 16 '12 at 10:33
  • @No, no copying required. See my answer below. You may need to beef up your Java knowledge to tackle this, this is quite basic inheritance stuff. – skaffman May 16 '12 at 10:37

2 Answers2

2

You should be able to subclass ServletContainer, override init, invoke the superclass method then perform your own logic, i.e.

public class MyServletContainer extends ServletContainer {

   public void init() throws ServletException {
      super.init();

      //... perform custom initialization logic here
   }
}
skaffman
  • 398,947
  • 96
  • 818
  • 769
0

Check if you have some of these jars "commons-annotation.jar, geronimo-annotation_1.1_spec, jboss-annotations-api_1.1_spec" in your webapp lib and remove.