Search code examples
javaspringspring-bootjavabeans

Disable required bean if bean does not exist


I have an EventProducer that sends messages via Kafka to all consumers. Now I want to be able to disable Kafka via application property. I disable the KafkaConfiguration bean via ConditionalOnProperty. The problem now is that the EventProducer throws an error because the KafkaConfiguration bean is not present, although the bean is not accessed when Kafka is disabled. ConditionalOnProperty does not exist for fields. How can I ignore the KafkaConfiguration in the EventProducer?

@Service
@RequiredArgsConstructor
public class EventProducer {

  @Value("${kafka.enabled}")
  private final boolean kafkaEnabled;
  
  private final KafkaConfiguration kafkaConfiguration;
  ...
}

@EnableKafka
@Configuration
@ConfigurationProperties(prefix = "kafka")
@ConditionalOnProperty(value = "kafka.enabled", havingValue = "true")
@RequiredArgsConstructor
public class KafkaConfiguration {
  ...
}

Solution

  • Use @Autowired(required = false), in which case the kafkaConfiguration field remain null if the KafkaConfiguration bean doesn't exist, meaning that field kafkaEnabled is redundant.

    @Service
    public class EventProducer {
    
      @Autowired(required = false)
      private KafkaConfiguration kafkaConfiguration;
    
      ...
    }
    

    Note that this code doesn't use constructor auto-wiring (removed @RequiredArgsConstructor), so the field is not final anymore.