{"id":3638,"date":"2025-12-24T10:00:52","date_gmt":"2025-12-24T15:00:52","guid":{"rendered":"https:\/\/www.mymiller.name\/wordpress\/?p=3638"},"modified":"2025-12-24T10:00:52","modified_gmt":"2025-12-24T15:00:52","slug":"master-the-art-of-conditional-beans-in-spring-with-annotation","status":"publish","type":"post","link":"https:\/\/www.mymiller.name\/wordpress\/springboot\/master-the-art-of-conditional-beans-in-spring-with-annotation\/","title":{"rendered":"Master the Art of Conditional Beans in Spring with Annotation"},"content":{"rendered":"\n<div class=\"wp-block-jetpack-markdown\"><p>In the dynamic world of Spring applications, managing which beans are active at runtime, how they are named, and how to precisely inject them is crucial. Spring offers a suite of conditional annotations, naming conventions, and injection mechanisms to achieve this flexibility. Let\u2019s delve into them:<\/p>\n<p><strong>Naming Beans<\/strong><\/p>\n<ul>\n<li>\n<p><strong>Default Naming:<\/strong> By default, Spring uses the following strategies to name beans:<\/p>\n<ul>\n<li><code>@Component<\/code>, <code>@Service<\/code>, <code>@Repository<\/code>, <code>@Controller<\/code>: The class name with the first letter lowercase (e.g., <code>myService<\/code> for <code>MyService<\/code>).<\/li>\n<li><code>@Bean<\/code>: The method name (e.g., <code>dataSource<\/code> for <code>@Bean public DataSource dataSource() { ... }<\/code>).<\/li>\n<\/ul>\n<\/li>\n<li>\n<p><strong>Custom Naming:<\/strong><\/p>\n<ul>\n<li><code>@Component<\/code>, <code>@Service<\/code>, etc.: Provide a value within the annotation (e.g., <code>@Service(&quot;myCustomService&quot;)<\/code>).<\/li>\n<li><code>@Bean<\/code>: Use the <code>name<\/code> attribute (e.g., <code>@Bean(name = &quot;myCustomBean&quot;)<\/code>).<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><strong>Specifying Beans by Name in Injection<\/strong><\/p>\n<p>When you have multiple beans of the same type, you need a way to tell Spring which one to inject. Here are the primary methods:<\/p>\n<ol>\n<li>\n<p><strong><code>@Qualifier<\/code><\/strong><\/p>\n<ul>\n<li>The most common and recommended approach.<\/li>\n<li>Use it with <code>@Autowired<\/code> or <code>@Inject<\/code>.<\/li>\n<li>Example:<\/li>\n<\/ul>\n<pre><code class=\"language-java\">@Autowired\n@Qualifier(&quot;myCustomBean&quot;)\nprivate MyBean myBean;\n<\/code><\/pre>\n<\/li>\n<li>\n<p><strong><code>@Resource<\/code><\/strong><\/p>\n<ul>\n<li>Offers similar functionality to <code>@Qualifier<\/code> but is part of the Java EE standard, not Spring-specific.<\/li>\n<li>Can also match by type if no name is provided.<\/li>\n<li>Example:<\/li>\n<\/ul>\n<pre><code class=\"language-java\">@Resource(name = &quot;myCustomBean&quot;)\nprivate MyBean myBean;\n<\/code><\/pre>\n<\/li>\n<\/ol>\n<p><strong>Conditional Bean Creation<\/strong><\/p>\n<p><strong>Conditional Bean Creation<\/strong><\/p>\n<p><strong>1. <code>@ConditionalOnProperty<\/code><\/strong><\/p>\n<ul>\n<li><strong>Use Case:<\/strong> Controls bean creation based on specific property values or the existence of a property.<\/li>\n<li><strong>Example:<\/strong><\/li>\n<\/ul>\n<pre><code class=\"language-java\">@Configuration\n@ConditionalOnProperty(name = &quot;feature.enabled&quot;, havingValue = &quot;true&quot;)\n@Primary \/\/ This bean will be the primary choice if multiple beans of the same type exist\npublic class FeatureBean { ... }\n<\/code><\/pre>\n<ul>\n<li><strong>Explanation:<\/strong> <code>FeatureBean<\/code> is only created if the property \u201cfeature.enabled\u201d exists and has the value \u201ctrue\u201d. If multiple beans of the same type are created, <code>FeatureBean<\/code> will be the primary choice due to the <code>@Primary<\/code> annotation.<\/li>\n<\/ul>\n<p><strong>2. <code>@ConditionalOnClass<\/code> and <code>@ConditionalOnMissingClass<\/code><\/strong><\/p>\n<ul>\n<li><strong>Use Case:<\/strong> Ideal for handling optional dependencies. A bean is created only if a specific class is present (or missing) in the classpath.<\/li>\n<li><strong>Example:<\/strong><\/li>\n<\/ul>\n<pre><code class=\"language-java\">@Configuration\n@ConditionalOnClass(name = &quot;com.example.OptionalDependency&quot;)\n@Primary \npublic class DependentBean { ... }\n<\/code><\/pre>\n<ul>\n<li><strong>Explanation:<\/strong> <code>DependentBean<\/code> is only created if the class \u201ccom.example.OptionalDependency\u201d is available. If multiple beans of the same type are created, <code>DependentBean<\/code> will be the primary choice.<\/li>\n<\/ul>\n<p><strong>3. <code>@ConditionalOnBean<\/code> and <code>@ConditionalOnMissingBean<\/code><\/strong><\/p>\n<ul>\n<li><strong>Use Case:<\/strong>  Enables you to create beans based on the presence (or absence) of other beans within the Spring context.<\/li>\n<li><strong>Example:<\/strong><\/li>\n<\/ul>\n<pre><code class=\"language-java\">@Configuration\n@ConditionalOnBean(DataSource.class)\n@Primary\npublic class DatabaseBean { ... }\n<\/code><\/pre>\n<ul>\n<li><strong>Explanation:<\/strong> <code>DatabaseBean<\/code> is only created if a bean of type <code>DataSource<\/code> already exists in the context. If multiple beans of the same type are created, <code>DatabaseBean<\/code> will be the primary choice.<\/li>\n<\/ul>\n<p><strong>4. <code>@Profile<\/code><\/strong><\/p>\n<ul>\n<li><strong>Use Case:<\/strong> While not strictly a conditional annotation, <code>@Profile<\/code> allows you to activate beans based on active Spring profiles.<\/li>\n<li><strong>Example:<\/strong><\/li>\n<\/ul>\n<pre><code class=\"language-java\">@Configuration\n@Profile(&quot;development&quot;)\n@Primary\npublic class DevBean { ... }\n<\/code><\/pre>\n<ul>\n<li><strong>Explanation:<\/strong> <code>DevBean<\/code> is only created when the \u201cdevelopment\u201d profile is active. If multiple beans of the same type are created, <code>DevBean<\/code> will be the primary choice.<\/li>\n<\/ul>\n<p><strong>The Role of <code>@Primary<\/code><\/strong><\/p>\n<p>In Spring, it\u2019s possible to have multiple beans of the same type within your application context. This can occur intentionally (e.g., providing different implementations for different scenarios) or unintentionally (e.g., third-party libraries contributing beans). When autowiring or injecting beans by type, Spring needs a way to determine which bean to use if there are multiple candidates.<\/p>\n<p>This is where <code>@Primary<\/code> comes in. When you annotate a bean with <code>@Primary<\/code>, you\u2019re essentially marking it as the preferred choice if there are multiple beans of the same type available. Spring will prioritize injecting the <code>@Primary<\/code> bean unless you explicitly specify a different bean using <code>@Qualifier<\/code> or <code>@Resource<\/code>.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre><code class=\"language-java\">@Configuration\n@Primary\npublic class DefaultEmailService implements EmailService { ... }\n\n@Configuration\npublic class BackupEmailService implements EmailService { ... }\n\n@Service\npublic class MyService {\n\n    @Autowired\n    private EmailService emailService; \/\/ This will inject DefaultEmailService\n\n    \/\/ ...\n}\n<\/code><\/pre>\n<p>In this example, both <code>DefaultEmailService<\/code> and <code>BackupEmailService<\/code> implement the <code>EmailService<\/code> interface. Since <code>DefaultEmailService<\/code> is marked with <code>@Primary<\/code>, it will be the one injected into <code>MyService<\/code> by default.<\/p>\n<p><strong>Important Considerations:<\/strong><\/p>\n<ul>\n<li><code>@Primary<\/code> only influences bean selection when there are multiple beans of the same type. It doesn\u2019t affect the creation or existence of the bean itself.<\/li>\n<li>You can combine <code>@Primary<\/code> with conditional annotations to create scenarios where a bean is only primary under certain conditions.<\/li>\n<li>If you have multiple <code>@Primary<\/code> beans of the same type, Spring will throw an exception during startup, indicating an ambiguous situation.<\/li>\n<li>Combining Annotations: Combine multiple conditional annotations for fine-grained control.<\/li>\n<li>Custom Conditions: Create custom conditions by implementing the <code>Condition<\/code> interface.<\/li>\n<\/ul>\n<p>Spring\u2019s conditional annotations, naming conventions, injection mechanisms (<code>@Qualifier<\/code>, <code>@Resource<\/code>), and the <code>@Primary<\/code> annotation provide a powerful toolkit for creating dynamic and adaptable applications. By mastering these tools, you gain precise control over your bean configuration, injection, and selection, allowing you to tailor your application to various environments and runtime conditions.<\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":3639,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_coblocks_attr":"","_coblocks_dimensions":"","_coblocks_responsive_height":"","_coblocks_accordion_ie_support":"","jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[448],"tags":[428,69,319],"series":[],"class_list":["post-3638","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-springboot","tag-beans","tag-java-2","tag-spring"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/08\/ai-generated-8981194_1280-jpg.avif","jetpack-related-posts":[{"id":3545,"url":"https:\/\/www.mymiller.name\/wordpress\/springboot\/conquering-dependency-injection-with-spring-a-beginners-guide\/","url_meta":{"origin":3638,"position":0},"title":"Conquering Dependency Injection with Spring: A Beginner&#8217;s Guide","author":"Jeffery Miller","date":"November 24, 2025","format":false,"excerpt":"Dependency Injection (DI) is often hailed as a superpower in the Spring framework, but it can seem mysterious to those new to it. Fear not! This guide will break down DI, show you its benefits, and get you started with real examples. What is Dependency Injection? Imagine you\u2019re building a\u2026","rel":"","context":"In &quot;Springboot&quot;","block_context":{"text":"Springboot","link":"https:\/\/www.mymiller.name\/wordpress\/category\/springboot\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/06\/vaccine-5763308_1280.jpg?fit=1200%2C675&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/06\/vaccine-5763308_1280.jpg?fit=1200%2C675&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/06\/vaccine-5763308_1280.jpg?fit=1200%2C675&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/06\/vaccine-5763308_1280.jpg?fit=1200%2C675&ssl=1&resize=700%2C400 2x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/06\/vaccine-5763308_1280.jpg?fit=1200%2C675&ssl=1&resize=1050%2C600 3x"},"classes":[]},{"id":3961,"url":"https:\/\/www.mymiller.name\/wordpress\/spring\/spring4\/architecting-spring-boot-4-with-official-spring-grpc-support\/","url_meta":{"origin":3638,"position":1},"title":"Architecting Spring Boot 4 with Official Spring gRPC Support","author":"Jeffery Miller","date":"January 15, 2026","format":false,"excerpt":"For years, the Spring community relied on excellent third-party starters (like net.devh) to bridge the gap between Spring Boot and gRPC. With the evolution of Spring Boot 4 and the official Spring gRPC project, we now have native support that aligns perfectly with Spring's dependency injection, observability, and configuration models.\u2026","rel":"","context":"In &quot;Spring4&quot;","block_context":{"text":"Spring4","link":"https:\/\/www.mymiller.name\/wordpress\/category\/spring\/spring4\/"},"img":{"alt_text":"","src":"https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2026\/01\/Gemini_Generated_Image_3yqio33yqio33yqi.avif","width":350,"height":200,"srcset":"https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2026\/01\/Gemini_Generated_Image_3yqio33yqio33yqi.avif 1x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2026\/01\/Gemini_Generated_Image_3yqio33yqio33yqi.avif 1.5x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2026\/01\/Gemini_Generated_Image_3yqio33yqio33yqi.avif 2x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2026\/01\/Gemini_Generated_Image_3yqio33yqio33yqi.avif 3x"},"classes":[]},{"id":3392,"url":"https:\/\/www.mymiller.name\/wordpress\/springboot\/spring-boot-caching\/","url_meta":{"origin":3638,"position":2},"title":"Spring Boot Caching","author":"Jeffery Miller","date":"December 24, 2025","format":false,"excerpt":"Caching is a crucial aspect of building high-performance applications, and Spring Boot provides excellent support for integrating caching into your projects seamlessly. In this article, we will explore how to leverage Spring Boot's caching capabilities effectively. We will cover the basics of caching annotations, configuration, and provide practical examples to\u2026","rel":"","context":"In &quot;Springboot&quot;","block_context":{"text":"Springboot","link":"https:\/\/www.mymiller.name\/wordpress\/category\/springboot\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2022\/02\/geocache-gd1a671d59_640.jpg?fit=640%2C360&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2022\/02\/geocache-gd1a671d59_640.jpg?fit=640%2C360&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2022\/02\/geocache-gd1a671d59_640.jpg?fit=640%2C360&ssl=1&resize=525%2C300 1.5x"},"classes":[]},{"id":3395,"url":"https:\/\/www.mymiller.name\/wordpress\/springboot\/spring-profiles-and-yaml\/","url_meta":{"origin":3638,"position":3},"title":"Spring Profiles and YAML","author":"Jeffery Miller","date":"December 24, 2025","format":false,"excerpt":"Configuration management is a critical aspect of building robust applications. Spring Boot simplifies configuration handling by supporting various file formats, including YAML. YAML (YAML Ain't Markup Language) offers a human-readable and concise syntax, making it an excellent choice for configuring Spring Boot applications. In this article, we will explore how\u2026","rel":"","context":"In &quot;Springboot&quot;","block_context":{"text":"Springboot","link":"https:\/\/www.mymiller.name\/wordpress\/category\/springboot\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2023\/06\/icon-gc4bfcbaa4_640.png?fit=640%2C640&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2023\/06\/icon-gc4bfcbaa4_640.png?fit=640%2C640&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2023\/06\/icon-gc4bfcbaa4_640.png?fit=640%2C640&ssl=1&resize=525%2C300 1.5x"},"classes":[]},{"id":3008,"url":"https:\/\/www.mymiller.name\/wordpress\/springboot\/spring-annotation-w-dynamic-service-loading\/","url_meta":{"origin":3638,"position":4},"title":"Spring Annotation w\/Dynamic Service Loading","author":"Jeffery Miller","date":"December 24, 2025","format":false,"excerpt":"Recently a project I was working on required the ability to load up a number of unknown services that implemented a Calendar Provider Interface. As this was a Spring server, I started looking around trying to find the right way to do this. I began by looking at being able\u2026","rel":"","context":"In &quot;Springboot&quot;","block_context":{"text":"Springboot","link":"https:\/\/www.mymiller.name\/wordpress\/category\/springboot\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/03\/computer-1343393_640.jpg?fit=640%2C360&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/03\/computer-1343393_640.jpg?fit=640%2C360&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/03\/computer-1343393_640.jpg?fit=640%2C360&ssl=1&resize=525%2C300 1.5x"},"classes":[]},{"id":3654,"url":"https:\/\/www.mymiller.name\/wordpress\/springboot\/spring-boot-actuator-crafting-custom-endpoints-for-tailored-insights\/","url_meta":{"origin":3638,"position":5},"title":"Spring Boot Actuator: Crafting Custom Endpoints for Tailored Insights","author":"Jeffery Miller","date":"December 24, 2025","format":false,"excerpt":"Spring Boot Actuator provides a robust set of built-in endpoints for monitoring and managing your applications. However, there are scenarios where you might need to expose application-specific information or metrics beyond what the standard endpoints offer. This is where custom actuator endpoints shine, allowing you to tailor the information you\u2026","rel":"","context":"In &quot;Springboot&quot;","block_context":{"text":"Springboot","link":"https:\/\/www.mymiller.name\/wordpress\/category\/springboot\/"},"img":{"alt_text":"","src":"https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/08\/oil-1183699_1280-jpg.avif","width":350,"height":200,"srcset":"https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/08\/oil-1183699_1280-jpg.avif 1x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/08\/oil-1183699_1280-jpg.avif 1.5x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/08\/oil-1183699_1280-jpg.avif 2x, https:\/\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2024\/08\/oil-1183699_1280-jpg.avif 3x"},"classes":[]}],"jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/posts\/3638","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/comments?post=3638"}],"version-history":[{"count":1,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/posts\/3638\/revisions"}],"predecessor-version":[{"id":3640,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/posts\/3638\/revisions\/3640"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/media\/3639"}],"wp:attachment":[{"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/media?parent=3638"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/categories?post=3638"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/tags?post=3638"},{"taxonomy":"series","embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/series?post=3638"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}