4

I would like to load inside my Spring MVC Web Application (packaged as WAR) some Spring framework beans annotated with @Service from an external jar, which is in charge of accessing a database and located in the classpath under /WEB-INF/lib. If possible, it would be desirable to load them automatically using the @Autowired annotation.

I have followed successfully the solution in this link1:

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

However, this solution uses Spring API function getBean which is considered a bad practice (see link2).

I also tried, without luck two more things to load the external jar´s applicationContext:

  • WAR´s appContext.xml:

    <import resource="classpath*:/WEB-INF/lib/pathToExternalJar/applicationContext.xml">
    
  • WAR´s web xml -> load the jar´s appContext as described here (link3). (e.g. *applicationContext.xml):

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

What is the best approach to load those beans properly and how should it be done?

Community
  • 1
  • 1
aloplop85
  • 892
  • 3
  • 16
  • 40

1 Answers1

3

WAR´s appContext.xml and WAR´s web xml are both feasible. If you need to run integration tests based on both localSpringContext.xml and external jar's applicationContext.xml frequently, I recommend the WAR´s appContext.xml approach.

Updated1:

WAR´s appContext.xml:

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

WAR´s web xml:

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

For example, if your applicationContext.xml is under package :com/gmail/hippoom

you can get it by classpath:com/gmail/hippoom/applicationContext.xml or classpath*:applicationContext.xml with wildcard.

Yugang Zhou
  • 7,123
  • 6
  • 32
  • 60
  • As I commented in the post I had no succeed using those approaches. How should the string entered as resource (in WAR´s appContext.xml approach) look like (please, provide an example)? Thanks. – aloplop85 Jul 10 '13 at 16:14
  • Well, the needed path was really my problem. I finally did it thanks to your help :) with: **** as the XML was directly under the JAR (currently, not inside any package as com/gmail/hippoom). So -> {classpath} = "". Now with that import I load perfectly the external applicationContext. Thanks again for your help. – aloplop85 Jul 11 '13 at 08:51