简体   繁体   English

从不同的模块自动装配bean

[英]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). 我使用spring和Jpa(Hibernate作为提供者)。 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. 我想出了一个结构,其中我有一个包含所有实体和dao类的核心模块,其他模块使用核心模块来实现持久性,并且每个模块都有自己的一组服务类和控制器。

在此输入图像描述

All Jpa and spring configuration files are in the core module. 所有Jpa和spring配置文件都在核心模块中。 With this setup I am facing a problem of autowiring dao beans in the modules making use of the core module. 通过这种设置,我面临着在使用核心模块的模块中自动装配dao bean的问题。 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)? 所以我的问题是,是否可以从其他模块中的核心模块自动装配bean(或者可能使用跨模块的上下文)? I am also open to suggestions regarding the structure, if there is a better way of doing it. 如果有更好的方法,我也愿意接受有关结构的建议。

Thanks 谢谢

The Core Module must be the parent Spring context that must be setted in each child context module. 核心模块必须是必须在每个子上下文模块中设置的父Spring上下文。 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 每个子上下文都可以从父级到达所有bean,但要注意父级无法看到子级

Depending on how you've configured your application, you can do this in several ways, ie 根据您配置应用程序的方式,您可以通过多种方式执行此操作,即

  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 将核心模块分配到单独的jar中,分配给每个模块,如本文所述, 跨多个Web应用程序共享弹出上下文
  2. Programatically, having your core spring xml in each child module, you can do this: 以编程方式,在每个子模块中拥有核心spring xml,您可以这样做:

     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(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM