Reputation: 2042
I know one of the purposes of Spring is to fail-fast if any bean initialization fails, but I'm curious if the following behavior is possible.
I have an application that depends on many external servers and DBs, and so there are a dozen beans that are interfaces for the different external services. Config values of the form 'db1.enabled=true' and 'db2.enabled=false' define whether these beans should even be initialized. What I want is a 'best effort' scenario where, if db1.enabled is set to true, but the db in question is not reachable for whatever reason and initialization of the bean that calls db1 fails, the whole system shouldn't crash. The effect should be as if db1.enabled was set to false, with ideally an error message somewhere indicating that this occurred. Doing this for all beans would defeat the purpose of Spring, but it would be useful for certain ones.
Upvotes: 2
Views: 2092
Reputation: 2724
If you use Java Config you can run basically any code as bean initialization. You can, for example, put something like this in your config:
@Configuration
public class MyConfig{
@Bean
public DataSource mainDataSource(){
try{
// initialize your basic datasource here
} catch(Exception e) {
// try something else here
}
}
}
Upvotes: 1