Java WAR-从外部JAR加载Spring Bean


问题内容

我想在我的Spring MVC Web应用程序(打包为WAR)中加载一些Spring框架bean @Service ,这些bean 由外部jar
注释,该jar负责访问数据库并 位于 / WEB-INF / lib下 的类路径中 。如果可能的话,希望使用
@Autowired 注释自动加载它们。

我已经成功地遵循了这个link1中的解决方案:

this.ctx = new ClassPathXmlApplicationContext("services-context.xml");
this.myAService = ctx.getBean("myAService");

但是,此解决方案使用Spring API函数 getBean,这被认为是不好的做法。

我还尝试了两件事来加载外部jar的applicationContext:

  • WAR的appContext.xml:

    <import resource="classpath*:/WEB-INF/lib/pathToExternalJar/applicationContext.xml">
    
  • WAR的Web xml->加载jar的appContext,如此处所述(link3)。(例如* applicationContext.xml):

        <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:localSpringContext.xml
            classpath:*applicationContext.xml
        </param-value>
    </context-param>
    

正确加载这些bean的最佳方法是什么,应该如何做?


问题答案:

WAR的appContext.xml和WAR的Webxml都是可行的。如果需要同时基于localSpringContext.xml和外部jar的applicationContext.xml运行集成测试,则建议使用WAR的appContext.xml方法。

更新1:

WAR的appContext.xml:

<import resource="classpath:{classpath}/applicationContext.xml"/>

WAR的Web xml:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:localSpringContext.xml
        classpath:{classpath}/applicationContext.xml
</param-value>
</context-param>

例如,如果您的applicationContext.xml在软件包:com / gmail / hippoom下

您可以通过带通配符的classpath:com / gmail / hippoom / applicationContext.xml或classpath
*:applicationContext.xml来获取。