Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowiring beans from a different module

I have a big application which i want to break up into manageable modules. I am using spring with Jpa (Hibernate as a provider). I came up with a structure where I have a core module containing all the entity and dao classes, and the other modules make use of the core module regarding persistence, and each one of them will have its own set of service classes and controllers.

enter image description here

All Jpa and spring configuration files are in the core module. With this setup I am facing a problem of autowiring dao beans in the modules making use of the core module. So my question is, is it possible to autowire beans from the core module in the other modules (or probably use a context across modules)? I am also open to suggestions regarding the structure, if there is a better way of doing it.

Thanks

like image 769
Chappex Avatar asked May 19 '12 15:05

Chappex


1 Answers

The Core Module must be the parent Spring context that must be setted in each child context module. By this way there's no ploblem with autowiring

Every child context can reach all beans from parent, but be aware of that parent can't see the children

Depending on how you've configured your application, you can do this in several ways, i. e.

  1. Distributing your core module in a separate jar to every module, as it's described in this article Sharing a spring context across multiple Webapps
  2. Programatically, having your core spring xml in each child module, you can do this:

    ClassPathXmlApplicationContext parentAppContext = new ClassPathXmlApplicationContext();
    parentAppContext.setConfigLocation("spring-core.xml"); // this is your core spring xml
    parentAppContext.refresh();
    ClassPathXmlApplicationContext moduleAppContext = new ClassPathXmlApplicationContext();
    moduleAppContext.setConfigLocation("others.xml");
    moduleAppContext.setParent(parentAppContext);
    moduleAppContext.refresh();
    
like image 161
richarbernal Avatar answered Oct 01 '22 20:10

richarbernal