如何在非Spring管理的Web应用程序中创建/加载自定义弹簧jar

时间:2014-10-17 15:42:57

标签: spring jar applicationcontext

我想使用spring创建一个jar lib,并在我的Web应用程序中导入它们。既然我也在后者使用弹簧,那么我没有任何问题。关键是我想在非弹簧管理环境中重复使用它。 让我们说我想在纯javaee web应用程序中使用lib,然后我就不能使用spring自动装配和打包扫描功能了。 我的想法是:在其costructor中创建一个简单的纯bean并加载spring配置:

public class SpringStandalone{

private Client                      client;
private AnnotationConfigApplicationContext  ctx;

public SpringStandalone() {
    ctx = new AnnotationConfigApplicationContext();
    ctx.getEnvironment().setActiveProfiles("test");
    ctx.scan("my.package.scan");
    ctx.refresh();
    client = (Client) ctx.getBean(Client.class);
    ctx.destroy();
}

public void send(Object o) {
    client.send(o);
}

}

这是正确的方法吗?如果是这样,我应该如何管理applicationContext destroy(我应该为此烦恼吗?)?

提前感谢您的帮助。

的Fabio

1 个答案:

答案 0 :(得分:1)

无法销毁Spring应用程序上下文,并希望您的Client对象能够正常运行。
相反,您应该提供单独的“ SpringStandalone.destroy()”方法,当您不再需要SpringStandalone类时,客户端代码将调用该方法。

请注意,对 ctx.destroy()的调用不仅会清除Spring容器,还会触发一些“业务”操作,例如调用所有使用 @PreDestroy <注释的bean方法/ em>,发布关闭事件等,因此当您不再需要SpringStandalone对象时调用它是一个好习惯。

我相信你的方法没有错。
请注意,加载Spring应用程序上下文需要一些时间,因此您只需要创建一次SpringStandalone。