如何在Spring中实现弹性bean? [英] How to implement a resilient bean in Spring?

查看:160
本文介绍了如何在Spring中实现弹性bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring bean,它在构造函数中通过http访问外部系统。
如果外部系统在启动时不可用,则无法创建bean并且应用程序无法正常启动。

I have a Spring bean that access an external system through http in its constructor. If the external system is not available at startup the bean cannot be created and application fails to start properly.

我希望我的应用程序能够启动外部系统。我宁愿缺少功能一段时间而不是重新启动应用程序。

I want my application to be able to start regardless of extenal systems. I would rather have missing functionality for a while than having to restart the application.

我知道这应该可以在Spring中实现,并且正确选择范围和代理bean工厂但我不确定实际上是怎么做到的。在我看来,Spring AOP的大多数部分旨在修改成功创建的目标,并且无法在创建期间处理激活或我错了吗?

I know this should be achievable in Spring with the right choice of scope and a proxying bean factory but I'm not sure how actually do it. It seems to me that most parts of Spring AOP is aimed at modifying targets that are succesfully created and is not able to handle excpetions during creation or am I wrong?

简而言之:我想要一个在第一次访问时创建目标bean的代理,然后只要它工作就保留该实例。如果它无法创建它,它应抛出异常并在下次调用代理时重试。

In short: I want a proxy that creates the target bean at first access and then retains that instance as long as it works. If it fails to create it, it should throw an exception and retry next time the proxy is called.

那么,您将如何实现此功能?

So, how would you implement this functionality?

推荐答案

我最终创建了一个ResilientBeanProxy,将实际的创建推迟到以后,所以是的,它几乎就像Spring的懒惰init一样,但附加功能是它在init期间处理异常。例如它不会停止创建应用程序上下文时在启动期间发生错误。

I ended up creating a ResilientBeanProxy that defer the actual creation to later, so yes, it is almost as Spring's lazy init but with the added feature that it handles exceptions during init. e.g. it will not halt the creation of the application context an error occurs during startup.

如果创建失败,将在下次调用时重试。

If the creation fails, it will be retried at the next invocation.

这篇关于如何在Spring中实现弹性bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆