目前我有一个实用程序 jar,其中包含许多数据存储服务。这些数据存储服务在幕后使用 Spring Data MongoDB,并且所有内容都使用实用程序 jar 中的 app-context.xml 文件进行配置。我希望这个实用程序 jar 能够更改后备存储,而不必更改使用此实用程序 jar 的任何内容。
现在,我想创建一个 spring mvc Web 应用程序,该应用程序使用此实用程序 jar 中的数据存储服务。
我该如何设置,以便 spring mvc Web 应用程序(或任何其他 jar)可以轻松使用数据存储服务,而不必了解太多关于实用程序 jar 的信息,但仍然可以正确加载实用程序 jar 中的 bean?
我正在考虑向实用程序 jar 添加一个新的 java bean 类,该类将在它自己的 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 中的 app-context.xml?有更好的方法吗?
由于没有人回答,我只是采用了我的方法,它似乎有效,尽管稍作修改以允许 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/war 中,使用以下内容创建 beaning:
<bean id="services" class="Services" destroy-method="destroy"/>
或者,如果您的其他 jar/war 不使用 spring,那么您可以执行以下操作:
Services s = new Services();
//... use your services, then clean up when done
s.myAService.doSomething();
s.destroy();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)