Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a resilient bean in Spring?

Tags:

java

spring

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.

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?

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?

like image 506
henrik_lundgren Avatar asked Nov 04 '22 18:11

henrik_lundgren


2 Answers

Have you tried lazy bean initiation?

<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>

you should not set this bean as property to Singleton bean because it will initiate it on startup.

like image 108
danny.lesnik Avatar answered Nov 11 '22 03:11

danny.lesnik


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.

like image 43
henrik_lundgren Avatar answered Nov 11 '22 05:11

henrik_lundgren