Component Scan not finding @Component's in a JAR in Tomcat webapp

AdrianRM picture AdrianRM · Jul 21, 2011 · Viewed 13.5k times · Source

I just filed a bug in the Spring bugsystem ( https://jira.springsource.org/browse/SPR-8551 ), but I am still unsure if I am missing something

I tracked down a problem with <context:component-scan/> to this statement. Given the two following classes which are in the same JAR in WEB-INF/lib of a web application (The JAR file has the directory structure):

test/TheBean.java:

package test;
@Component
public class TheBean{
}

test/BeanSearcher.java:

package test;
public class BeanSearcher{

  public void init(){ 
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); 
    ctx.scan("test"); 
    ctx.refresh(); 
    TheBean b=  ctx.getBean(TheBean.class); 
    // What is the value of b? 
  }
}

If I run new BeanSearcher().init() in a jUnit test case or other type of standalone application, b is getting assigned an instance of TheBean, but if I run it, say, in a JSP, ctx.getBean() is returning null.

So, am I doing something wrong or not taking something into account, is this just a bug...?

EDIT 8/8/2011: It seems to work good as I tried to simplify the problem, but still, when I try to make it work, in the initialization of OpenCms, it fails. Now I am trying to look for the differences between working versions and the one which doesn't work. (Classloader, ubication of the relevant classes in different JARs or directly in WEB-INF/classes, calls via reflection, etc.)

Answer

AdrianRM picture AdrianRM · Dec 24, 2012

As I wrote in the comment, the solution is given by the answer here: Spring Annotation-based controllers not working if it is inside jar file

When you export the jar file using the export utility in eclipse there is a option called Add directory entries.