{"id":218,"date":"2024-06-20T21:16:12","date_gmt":"2024-06-21T00:16:12","guid":{"rendered":"https:\/\/springmasteryhub.com\/?p=218"},"modified":"2024-06-20T21:16:12","modified_gmt":"2024-06-21T00:16:12","slug":"understanding-primary-in-spring","status":"publish","type":"post","link":"https:\/\/springmasteryhub.com\/?p=218","title":{"rendered":"Understanding @Primary in Spring"},"content":{"rendered":"\n<p>If you read my post about the <code>@Qualifier<\/code> annotation, you have noticed that defining two beans of the same type can be a challenge. By distinguishing it with a qualifier name, <code>@Qualifier<\/code> helps Spring determine which bean to inject.<\/p>\n\n\n\n<p>The <code>@Primary<\/code> annotation will help Spring decide which of those same types of beans it should pick primarily.<\/p>\n\n\n\n<p>For the bean annotated with the <code>@Primary<\/code> annotation, the <code>@Qualifier<\/code> will not be necessary. It is only required for the other bean.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example 1: Using @Primary and @Qualifier in Spring<\/h3>\n\n\n\n<p>Let\u2019s see the example in practice:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic interface GreetingService {\n    String greet();\n}\n\n@Service\n@Primary\npublic class EnglishGreetingService implements GreetingService {\n    @Override\n    public String greet() {\n        return &quot;Hello!&quot;;\n    }\n}\n\n@Service(&quot;spanishGreetingService&quot;)\npublic class SpanishGreetingService implements GreetingService {\n    @Override\n    public String greet() {\n        return &quot;Hola!&quot;;\n    }\n}\n\n@RestController\n@RequestMapping(&quot;\/greet&quot;)\npublic class GreetingController {\n\n    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(GreetingController.class);\n    \n    @Autowired\n    private GreetingService greetingService; \n    \n    @Autowired\n    @Qualifier(&quot;spanishGreetingService&quot;)\n    private GreetingService spanishGreetingService; \n\n    @GetMapping\n    public ResponseEntity&lt;String&gt; printGreetings() {\n        log.info(greetingService.greet()); \n        log.info(spanishGreetingService.greet()); \n        return ResponseEntity.ok(&quot;greetings&quot;);\n    }\n}\n\n<\/pre><\/div>\n\n\n<p>You won\u2019t need to use the <code>@Qualifier<\/code> on the bean you defined as <code>@Primary<\/code><\/p>\n\n\n\n<p>When you call this controller with this curl:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\ncurl &lt;http:\/\/localhost:8080\/greet&gt;\n\n<\/pre><\/div>\n\n\n<p>You are going to see in the logs that the primary one was automatically set:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n2024-06-20T21:08:53.884-03:00  INFO 1868 --- &#x5B;nio-8080-exec-1] c.s.mastery.primary.GreetingController   : Hello!\n2024-06-20T21:08:53.884-03:00  INFO 1868 --- &#x5B;nio-8080-exec-1] c.s.mastery.primary.GreetingController   : Hola!\n\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Example 2: Using @Primary at the Configuration Level<\/h3>\n\n\n\n<p>Another example is when you need to use the bean at the configuration level, so it will not be possible to use the <code>@Qualifier<\/code> to identify which bean Spring should inject.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Configuration\npublic class AppPrimaryConfig {\n    @Bean\n    @Primary\n    public ConfigGreetingService portugueseGreetings() {\n        return new PortugueseGreetings();\n    }\n\n    @Bean(&quot;italianGreetings&quot;)\n    public ConfigGreetingService italianGreetings() {\n        return new ItalianGreetings();\n    }\n\n}\n\n@RestController\n@RequestMapping(&quot;\/new-greetings&quot;)\npublic class NewGreetingController {\n\n    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(GreetingController.class);\n    @Autowired\n    private ConfigGreetingService greetingService;\n\n    @Autowired\n    @Qualifier(&quot;italianGreetings&quot;)\n    private ConfigGreetingService italianGreetings;\n\n    @GetMapping\n    public ResponseEntity&lt;String&gt; printGreetings() {\n        log.info(greetingService.greet());\n        log.info(italianGreetings.greet());\n        return ResponseEntity.ok(&quot;greetings&quot;);\n    }\n}\n\n\n<\/pre><\/div>\n\n\n<p>When you call the controller:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncurl &lt;http:\/\/localhost:8080\/new-greetings&gt;\n\n<\/pre><\/div>\n\n\n<p>You should see:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n2024-06-20T21:10:17.517-03:00  INFO 8768 --- &#x5B;nio-8080-exec-1] c.s.mastery.primary.GreetingController   : Ola\n2024-06-20T21:10:17.517-03:00  INFO 8768 --- &#x5B;nio-8080-exec-1] c.s.mastery.primary.GreetingController   : Ciao\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>In this blog post, you learned about the <code>@Primary<\/code> annotation and its use cases.<\/p>\n\n\n\n<p>If you like this topic, make sure to follow me. In the following days, I\u2019ll be explaining more about Spring annotations! Stay tuned!<\/p>\n\n\n\n<p><a href=\"https:\/\/twitter.com\/WillianFMoya\">Willian Moya (@WillianFMoya) \/ X (twitter.com)<\/a><\/p>\n\n\n\n<p><a href=\"https:\/\/www.linkedin.com\/in\/willianmoya\/\">Willian Ferreira Moya | LinkedIn<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you read my post about the @Qualifier annotation, you have noticed that defining two beans of the same type can be a challenge. By distinguishing it with a qualifier name, @Qualifier helps Spring determine which bean to inject. The @Primary annotation will help Spring decide which of those same types of beans it should [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_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":""},"categories":[6],"tags":[13,18,20,22,23,24],"class_list":["post-218","post","type-post","status-publish","format-standard","hentry","category-spring","tag-java","tag-programming","tag-software-development","tag-spring-boot","tag-spring-framework","tag-springboot"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=\/wp\/v2\/posts\/218","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=218"}],"version-history":[{"count":0,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=\/wp\/v2\/posts\/218\/revisions"}],"wp:attachment":[{"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=218"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=218"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=218"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}