Search code examples
javaspringapplicationcontext

Spring - Use applicationContext from .jar file added as a dependency


Imagine a situation where there are 2 independent modules - Module A and B. Both of them are constructed using Spring. Each of them have its own applicationContext - Module A works with applicationContextA and B - applicationContextB.
Module A contains facade class - defined in a bean moduleAFacade - that provides some functionality of Module A. Module B needs to access the functionality of Module A.
Let's have Module A added as a .jar dependency in the module B. There is this construction in applicationContextB:

<bean id="moduleBBeanUsingModuleAfacade" class="com.example.moduleB">
    <property name="moduleAFacadeObject" ref="moduleAFacade" />
</bean>

But applicationContext of Module A is not accessible from Module B's appContext directly. I need to use something like

<import resource="classpath*:moduleAApplicationContext.xml" /> 

Are there any other methods to access application contexts of .jar files added to the project as dependency?
Are there some best practises how to accomplish the task?



Solution

  • You can define a configuration file in module A

    package you.organisation.moduleA.config;
    @Configuration
    @ImportResource("classpath:path/to/applicationContextA.xml")
    public class ModuleAConfig implements Serializable {
    
    }
    

    and in the module B context file, you can access module A beans

    <context:component-scan base-package="you.organisation.*.config" />
    

    If you want to use Module B config files, tou do the same

    package you.organisation.moduleB.config;
    @Configuration
    @ImportResource("classpath:path/to/applicationContextB.xml")
    public class ModuleBConfig implements Serializable {
    
    }
    

    and in the module that will use it

    <context:component-scan base-package="you.organisation.*.config" />
    

    About best practices you must be careful when using wildcards, please have a look to the section 4.7.2.2