Back to all reviewers

Concrete bean return types

spring-projects/spring-boot
Based on 6 comments
Java

When defining `@Bean` methods in Spring configurations, use concrete return types rather than interfaces while using interface types in `@ConditionalOnMissingBean` annotations. This approach maximizes type information available to the Spring bean factory while maintaining flexibility in bean overriding.

Spring Java

Reviewer Prompt

When defining @Bean methods in Spring configurations, use concrete return types rather than interfaces while using interface types in @ConditionalOnMissingBean annotations. This approach maximizes type information available to the Spring bean factory while maintaining flexibility in bean overriding.

For example, instead of:

@Bean
@ConditionalOnMissingBean
PulsarConsumerFactory<?> pulsarConsumerFactory(PulsarClient pulsarClient) {
    return new DefaultPulsarConsumerFactory<>(/* parameters */);
}

Prefer:

@Bean
@ConditionalOnMissingBean(PulsarConsumerFactory.class)
DefaultPulsarConsumerFactory<?> pulsarConsumerFactory(PulsarClient pulsarClient) {
    return new DefaultPulsarConsumerFactory<>(/* parameters */);
}

This provides Spring with precise type details during bean creation while allowing applications to override the bean with any implementation of the interface. The bean factory will have more complete information about the actual implementation, which helps with autowiring, debugging, and type safety throughout the application context.

6
Comments Analyzed
Java
Primary Language
Spring
Category

Source Discussions