组件扫描在 Tomcat web 应用程序的 JAR 中找不到 @Component
我刚刚在 Spring 错误系统中提交了一个错误 ( https://jira.springsource.org/browse/SPR -8551 ),但我仍然不确定我是否遗漏了一些
我用
追踪到此语句的问题的内容。 给定以下两个类,它们位于 Web 应用程序的 WEB-INF/lib 中的同一 JAR 中(JAR 文件具有目录结构):
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?
}
}
如果我运行 new BeanSearcher().init() 在 jUnit 测试用例或其他类型的独立应用程序中,b 被分配了一个 TheBean 实例,但是如果我在 JSP 中运行它,
ctx.getBean()
返回 null。
那么,我是做错了什么还是没有考虑到某些事情,这只是一个错误......?
编辑 8/8/2011:它似乎工作得很好,因为我试图简化问题,但是当我尝试使其工作时,在 OpenCms 的初始化中,它失败了。现在我正在尝试寻找工作版本和不起作用版本之间的差异。 (类加载器、不同 JAR 中或直接在 WEB-INF/classes 中相关类的泛化、通过反射调用等)
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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如我在评论中所写,解决方案由此处的答案给出:
基于 Spring 注解的控制器在以下情况下不起作用它在 jar 文件内
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
明显的问题是你的 web.xml 中是否有类似的东西:
没有这些,Spring 实际上根本不会加载,更不用说正确构建 bean 了……
The obvious question is whether you have things like these in your web.xml:
Without these, Spring won't actually load at all, let alone properly build beans…