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

标签 java spring spring-data-mongodb

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

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

我如何设置它以便 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 的?有更好的方法吗?

最佳答案

由于没有人回答,我只是采用我的方法,它似乎有效,但稍作修改以允许 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();

关于java - 如何从外部实用程序 jar 正确加载和配置 Spring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17374458/

相关文章:

java - 如何在swing中将元素添加到JList?

java - 上传的文件丢失

java - 从 Tiles View (JSP) 访问 Spring bean

java - 带有 Java 外键的 MongoDb

mongodb - Spring-Data:指定 MongoRepository 应该使用哪个 MongoTemplate

java - Spring Data Mongodb 的性能问题

java - 如何在 Wildfly-8.2.1.Final 上设置域名(或主机名)

java - 此类上获取线程已启动错误?

java - Spring Boot 中的单元测试在服务中抛出异常时给出错误

c# - Spring.Net 中包含通用字典的通用字典