Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.)

like image 646
AdrianRM Avatar asked Jul 21 '11 09:07

AdrianRM


People also ask

Where to place JAR files in Tomcat?

Tomcat JAR deployment options Package the JAR file in the WEB-INF\lib folder of the Java web application; Place the JAR file in the \lib subfolder of the Apache Tomcat installation; Configure a folder for shared JAR files by editing Tomcat's common.

Do we need to deploy JAR file in Tomcat?

Apache tomcat is a web container you cannot deploy a jar in tomcat server. If you created a web application then export your application as war file and put it in tomcat webapp directory, start the server and your war will be deployed.

How do I use context component scan?

Put this “ context:component ” in bean configuration file, it means, enable auto scanning feature in Spring. The base-package is indicate where are your components stored, Spring will scan this folder and find out the bean (annotated with @Component) and register it in Spring container.


1 Answers

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.

like image 186
AdrianRM Avatar answered Oct 04 '22 21:10

AdrianRM