Search code examples
javaspringclasspathapplicationcontext

How to access Spring context from a depending project?


Suppose I have two projects:

ProjectA and ProjectB
ProjectA depends on ProjectB

And I have a context.xml locates at ProjectB/target/test-classes/context.xml. Now I need to loat the context from ProjectA. In projectB I have an accesser class:

Class ContextAccessor{
    ApplicationContext context = new
        ClassPathXmlApplicationContext("context.xml");

    public static ApplicationContext getContext(){
        return context;
    }
}

While in ProjectA, I'm trying to get the context using:

ContextAccessor.getContext();

but it throws an exception with message:

Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException     parsing XML document from class path resource [context.xml]; nested exception is java.io.FileNotFoundException: class path resource [context.xml] cannot be opened because it does not exist
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
at 

Please give suggestions. Appreciation.


Solution

  • I finally solved this issue by using:

    Class ContextAccessor{
        ApplicationContext context = new
            FileSystemXmlApplicationContext(this.getClass().getProtectionDomain().
            getCodeSource().getLocation().getPath());
    
        public static ApplicationContext getContext(){
            return context;
        }
    }
    

    Assuming the context is at ProjectB/target/classes/context.xml