Search code examples
javaspringjavabeans

How to silently cancel bean creation?


@Component
public class MyBean {

  @Autowired
  public MyBean(@Value("${optional:#{null}}") String optional) {
    if (optional == null) {
      // cancel bean creation?
    }
  }

}

How to silently cancel bean creation? I could throw a RuntimeException, but I don't want this cancellation to be considered as an error: the bean must just not be created, the application initialization must go on.


Solution

  • Here you can make use of @Conditional

    Step 1- Implement Condition.matches so as to specify when should the bean be created or not.

    public class SomeCondition implements Condition {
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            return System.getProperty("optional") != null;
        }
    }
    

    The condition class is referred as direct class (not as spring bean) so it can't use the @Value property injection. See here for alternative

    Step 2 - In the configuration class specify the above class as condition to decide the bean creation

    @Configuration
    public class SomeAppConfig {
    
        @Bean
        @Condition(SomeCondition.class)
        public MyBean myBean() {
          return new MyBean();
        }
    }
    

    P.S.: I have assumed that you use Java config.