Spring Autowire停止为Tomcat类路径上的类工作 [英] Spring autowire stops working for classes on the Tomcat classpath
问题描述
在我的库FooLibrary.jar
内部,Spring实例化了具有属性bars
的类com.example.FooImpl
.我有很多Bar
实例,这些实例也由Spring实例化.一组条状线会自动连接到FooImpl
中,如下所示:
Inside my library FooLibrary.jar
Spring instantiates class com.example.FooImpl
which has a property bars
. I have lots of Bar
instances also instantiated by Spring. A set of bars is autowired into FooImpl
like this:
@Component
public class FooImpl {
@Inject
private Set<Bar> bars;
在独立应用程序中,Spring实例化Bar
实例,实例化FooImpl
实例,然后使用Bar
的集合自动装配FooImpl.bars
.可以.
In a standalone application, Spring instantiates the Bar
instances, instantiates the FooImpl
instances, and then autowires FooImpl.bars
with the set of Bar
s. It works.
现在,我正在Tomcat内的webapp中运行相同的Spring配置. FooLibrary.jar
位于WEB-INF/lib
内部,并且所有内容均按上述概述继续工作.
Now I'm running the same Spring configuration in a webapp inside Tomcat. FooLibrary.jar
is inside WEB-INF/lib
, and everything continues to work as outlined above.
问题是该Web应用使用JavaCompiler
,无法自动找到其依赖项来自动编译某些类除非我将该库放在启动Tomcat路径上.我将FooLibrary.jar
添加到Tomcat类路径的那一刻(例如,在Eclipse内Tomcat的启动配置中,或者如果独立运行Tomcat,则假定startup.sh
或setclasspath.bat
),自动装配停止工作.
The problem is that the web app automatically compiles somes classes using JavaCompiler
, which can't find its dependencies for dynamically compiling unless I place that library on the startup Tomcat path. The minute I add FooLibrary.jar
to the Tomcat classpath (e.g. in in the launch configuration of Tomcat inside Eclipse, or I presume startup.sh
or setclasspath.bat
if running Tomcat standalone), autowire stops working.
也就是说,当我的Web应用程序启动时,Spring将创建所有Bar
实例,然后实例化FooImpl
,但是从不将的集合自动关联到. 知道为什么吗?
That is, when my webapp starts up, Spring creates all the Bar
instances, then instantiates FooImpl
, but never autowires the set of Bar
s into FooImpl.bars
. Any idea why?
(这与从Webapp类加载器启动Spring ContextLoaderListener
有什么关系,但我想知道FooImpl
和Bar
实例是从Tomcat类加载器启动的吗?)
(Does it have something to do with the Spring ContextLoaderListener
being started from the webapp classloader, but the FooImpl
and Bar
instances coming from the Tomcat classloader, I wonder?)
推荐答案
由于类型不兼容(例如,在多个类加载器中加载的类),自动装配可能会失败.
Autowiring can fail due to incompatible types (e.g. classes loaded in multiple classloaders).
由于您已经将JAR放置在tomcat的启动类路径中,因此web应用程序也必须可见该JAR,而不必将JAR放置在WEB-INF/lib中.
Since you already place the JAR in tomcat's boot classpath, it must be visible to the webapp as well without you having to place the JAR in WEB-INF/lib.
您可以将依赖项范围provided
设置为不让Maven放置在WEB-INF/lib中.
You can make the dependency scope provided
to not have Maven place it in WEB-INF/lib.
这篇关于Spring Autowire停止为Tomcat类路径上的类工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!