How do I configure a @Bean if it's accepted to fail initialisation?

Viewed 59

I have some code that initialises a Google Authentication IdTokenProvider (the type of object is unrelated to my question). However, given the current state of my application, it's not the end of the world if the provider fails to initialise. For example:

@Configuration
public class GoogleConfiguration {

  @Bean
  public IdTokenProvider idTokenProvider() {
    // this can throw
    return GoogleAuthUtils.getIdTokenProvider();
  }
}

@RequiredArgsConstructor
public class SomeConsumer {

  private IdTokenProvider idTokenProvider;

  @Autowired(required = false)
  public void setIdTokenProvider(IdTokenProvider idTokenProvider) {
    this.idTokenProvider = idTokenProvider;
  }

  //...magic
}

One possible solution (which works), is to wrap the throwing code and return null, e.g.

@Slf4j
@Configuration
public class GoogleConfiguration {

  @Bean
  public IdTokenProvider idTokenProvider() {
    try {
      return GoogleAuthUtils.getIdTokenProvider();
    } catch (Exception e) {
      log.error("Failed to create an 'IdTokenProvider'", e);
      return null;
    }
  }
}

Is it a good pattern to return null beans. I believe spring registers the bean, but its value is actually null rather than an instance of IdTokenProvider. Is there a way to avoid registering the bean if it fails instantiation?

1 Answers
Related