如何从外部实用程序jar正确加载和配置Spring bean

目前我有一个包含许多数据存储区服务的实用程序jar。 在幕后,这些数据存储区服务使用Spring Data MongoDB,并且所有内容都使用实用程序jar中的app-context.xml文件进行配置。 我希望这个实用程序jar能够更改后备存储,而无需更改使用此实用程序jar的任何内容。

现在,我想创建一个使用此实用程序jar中的数据存储区服务的spring mvc Web应用程序。

我如何设置它,以便spring mvc web应用程序(或任何其他jar)可以轻松使用数据存储区服务,而无需了解实用程序jar,但仍然可以正确加载实用程序jar中的bean?

我正在考虑向实用程序jar中添加一个新的java bean类,它将app-context加载到它自己的jar中,然后为服务设置一些属性。 然后spring mvc将在我的实用程序jar中使用这个新类创建一个bean,并通过这个bean引用服务。

/** * This bean would exist in the utility jar, and other jars/webapps would * create a new instance of this bean. */ public class Services { private MyAService myAService; private MyBService myBService; public Services() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("app-context.xml"); // these are configured in the app-context.xml this.myAService = ctx.getBean("myAService"); this.myBService = ctx.getBean("myBService"); } } 

这是一个很好的方法吗? 好像我现在有两个spring应用程序上下文,那可以吗? 如何确保加载正确的app-context.xml,而不是另一个jar加载? 有更好的方法吗?

由于没有人回答,我只是采用我的方法,它似乎工作,虽然稍作修改,允许bean正确破坏内部上下文。

在您的实用程序jar中创建一个加载应用程序上下文xml的类,如下所示:

 public class Services implements DisposableBean { ClassPathXmlApplicationContext ctx; private MyAService myAService; private MyBService myBService; public Services() { this.ctx = new ClassPathXmlApplicationContext("services-context.xml"); // these are configured in the services-context.xml this.myAService = ctx.getBean("myAService"); this.myBService = ctx.getBean("myBService"); } // Add getters for your services @Override public void destroy() throws Exception { this.myAService = null; this.myBService = null; this.ctx.destroy(); this.ctx = null; } } 

确保您的“services-context.xml”文件在类路径中是唯一的。 您可以通过将其放在与包结构匹配的文件夹结构中来完成此操作。

在你的另一个jar子/战争中,使用以下内容创建beaning:

  

或者,如果你的其他jar / war不使用spring,那么你会做类似的事情:

 Services s = new Services(); //... use your services, then clean up when done s.myAService.doSomething(); s.destroy(); 

您可以通过两种方法解决此问题:(请将依赖项作为pom.xml的一部分包含在内)

  1. 仅使用引用这些类路径的路径手动将所需的实用程序bean包含到此新的application-context.xml中。 这只是创造选择性豆类的spring之美。

  2. 有一个属性文件(在新的application-context.xml中包含它)

并定义路径ao实用程序jar

 application.path.of.utility.jar=/utility/jar/path/application_context.xml