Spring Autowiring 停止为 Tomcat 类路径上的类工作

标签 spring tomcat classpath autowired inject

在我的库 FooLibrary.jar 中,Spring 实例化类 com.example.FooImpl,它有一个属性 bars。我有很多 Bar 实例也由 Spring 实例化。一组柱状图自动连接到 FooImpl 中,如下所示:

@Component
public class FooImpl {
  @Inject
  private Set<Bar> bars;

在独立应用程序中,Spring 实例化 Bar 实例,实例化 FooImpl 实例,然后使用以下集合 Autowiring FooImpl.bars 条形图。它有效。

现在,我在 Tomcat 内的 Web 应用程序中运行相同的 Spring 配置。 FooLibrary.jar 位于 WEB-INF/lib 内,并且一切继续如上文所述工作。

问题是 Web 应用程序使用 JavaCompiler 自动编译一些类,which can't find its dependencies for dynamically compiling除非我将该库放在启动 Tomcat 路径上。我将 FooLibrary.jar 添加到 Tomcat 类路径的那一刻(例如,在 Eclipse 中 Tomcat 的启动配置中,或者我假设 startup.shsetclasspath.bat 如果独立运行 Tomcat), Autowiring 将停止工作。

也就是说,当我的 webapp 启动时,Spring 创建所有 Bar 实例,然后实例化 FooImpl,但从不 Autowiring BarFooImpl.bars知道为什么吗?

(它是否与从 webapp 类加载器启动的 Spring ContextLoaderListener 有关,但是 FooImplBar 实例来自Tomcat 类加载器,我想知道?)

最佳答案

由于类型不兼容(例如在多个类加载器中加载的类), Autowiring 可能会失败。

因为您已经将 JAR 放在 tomcat 的引导类路径中,所以它也必须对 webapp 可见,而不必将 JAR 放在 WEB-INF/lib 中。

您可以使依赖范围provided 不让 Maven 将它放在 WEB-INF/lib 中。

关于Spring Autowiring 停止为 Tomcat 类路径上的类工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17029828/

相关文章:

java - 如何使整个文件夹及其后代可供 UIMA(Ruta、Uimafit)作为资源使用?

spring - @Retryable 没有被触发

java - 在 Spring Security 中配置自定义对象

windows - 几个小时后 tomcat 6 挂起

java - 从 Java 6 + Tomcat 6 升级到 Java 8 + Tomcat 8 时垃圾收集器的使用

windows - 如何将 gperf 添加到 Windows 7 类路径(并在 DOS 中识别它)

java - Spring FileSystemXmlApplicationContext getBeanDefinitionNames 返回空数组

java - Spring 配置的 Hibernate 方言问题

启动tomcat加载servlet时出现java.lang.ClassCastException

java - Tiny OS中使用java读取串口数据