How to properly load and configure Spring beans from an external utility jar

牧云@^-^@ 提交于 2019-12-04 12:47:54

Since nobody has answered, I just went with my approach and it seems to work, though with a slight modification to allow the bean to destroy the internal context properly.

In your utility jar create a class that loads the app context xml like so:

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;
    }
}

Make sure your "services-context.xml" file is unique on the classpath. You can do this by putting it in a folder structure that matches the package structure.

In your other jar/war, create the beaning using something like:

<bean id="services" class="Services" destroy-method="destroy"/>

Or, if your other jar/war doesn't use spring, then you do something like:

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

Two approaches by which you can solve this : (Please include the dependency as part of pom.xml)

  1. To manually include only the required utility beans into this new application-context.xml with the path referring to those class paths. That's the beauty of spring to create the selective bean only.

  2. Have a properties file (Include this in the new application-context.xml)

<context:property-placeholder location="WEB-INF/utility.properties"/>

<import resource="${application.path.of.utility.jar}"/>

And define path ao the utility jar

application.path.of.utility.jar=/utility/jar/path/application_context.xml
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!