{"id":214,"date":"2024-06-19T14:00:00","date_gmt":"2024-06-19T17:00:00","guid":{"rendered":"https:\/\/springmasteryhub.com\/?p=214"},"modified":"2024-06-19T14:00:00","modified_gmt":"2024-06-19T17:00:00","slug":"using-qualifier-to-resolve-bean-conflicts-in-spring","status":"publish","type":"post","link":"https:\/\/springmasteryhub.com\/?p=214","title":{"rendered":"Using @Qualifier to Resolve Bean Conflicts in Spring"},"content":{"rendered":"\n<p>When working on a Spring project, you might encounter a situation where you have multiple bean implementations for the same type.<\/p>\n\n\n\n<p>This can cause an error because Spring doesn&#8217;t know which bean to inject. To solve this, we use the <code>@Qualifier<\/code> annotation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The Problem<\/h3>\n\n\n\n<p>Let&#8217;s say you have an interface <code>MessageService<\/code> that your application uses to send messages, and you have multiple ways to send messages, such as Email, SMS, Push, etc.<\/p>\n\n\n\n<p>For each of these channels, you have an implementation of the interface like <code>EmailMessageService<\/code> and <code>SmsMessageService<\/code>.<\/p>\n\n\n\n<p>Consider this scenario. You have a MessageService that defines a standard to send messages for all methods.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\npublic interface MessageService {\n    void sendMessage(String to, String message);\n}\n\n@Service(&quot;emailService&quot;)\npublic class EmailMessageService implements MessageService {\n    @Override\n    public void sendMessage(String to, String message) {\n        System.out.println(&quot;Sending email to: &quot; + to + &quot; with message: &quot; + message);\n    }\n}\n\n@Service(&quot;smsService&quot;)\npublic class SmsMessageService implements MessageService {\n    @Override\n    public void sendMessage(String to, String message) {\n        System.out.println(&quot;Sending SMS to: &quot; + to + &quot; with message: &quot; + message);\n    }\n}\n\n\n<\/pre><\/div>\n\n\n<p>If you try to use these services in the components like this:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\n@Service\npublic class OrderService {\n\n    private final MessageService messageService;\n\n    @Autowired\n    public OrderService(MessageService messageService) {\n        this.messageService = messageService;\n    }\n\n    public void sendOrderConfirmation(String email, String message) {\n        messageService.sendMessage(email, message);\n    }\n}\n\n@Service\npublic class ForgetPasswordService {\n\n    private final MessageService messageService;\n\n    @Autowired\n    public ForgetPasswordService(MessageService messageService) {\n        this.messageService = messageService;\n    }\n\n    public void sendResetPasswordLink(String phoneNumber, String message) {\n        messageService.sendMessage(phoneNumber, message);\n    }\n\n}\n\n\n<\/pre><\/div>\n\n\n<p>You will get an error, and a message like that will pop up at your application startup:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\n***************************\nAPPLICATION FAILED TO START\n***************************\n\nDescription:\n\nParameter 0 of constructor in com.spring.mastery.qualifier.OrderService required a single bean, but 2 were found:\n    - emailService: defined in file &#x5B;...\\\\EmailMessageService.class]\n    - smsService: defined in file &#x5B;...\\\\SmsMessageService.class]\n\n\n<\/pre><\/div>\n\n\n<p>Spring doesn&#8217;t know which bean to use. There are two beans of the same type.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Using @Qualifier<\/h3>\n\n\n\n<p>By using <code>@Qualifier<\/code>, you can specify the name of the bean to be injected. Here&#8217;s how you can do it:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\n@Service\npublic class OrderService {\n\n    private final MessageService messageService;\n\n    @Autowired\n    public OrderService(@Qualifier(&quot;emailService&quot;) MessageService messageService) {\n        this.messageService = messageService;\n    }\n\n    public void sendOrderConfirmation(String email, String message) {\n        messageService.sendMessage(email, message);\n    }\n}\n\n@Service\npublic class ForgetPasswordService {\n\n    private final MessageService messageService;\n\n    @Autowired\n    public ForgetPasswordService(@Qualifier(&quot;smsService&quot;) MessageService messageService) {\n        this.messageService = messageService;\n    }\n\n    public void sendResetPasswordLink(String phoneNumber, String message) {\n        messageService.sendMessage(phoneNumber, message);\n    }\n\n}\n\n\n<\/pre><\/div>\n\n\n<p>Now, Spring knows which bean to inject in each component, allowing you to have multiple implementations of the same bean.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Variations<\/h3>\n\n\n\n<p>There are a few other ways to help Spring identify which bean to inject.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Field Injection with @Autowired and @Qualifier:<\/strong><\/h3>\n\n\n\n<p>This is one of the most common ones.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\n@Autowired\n@Qualifier(&quot;emailService&quot;)\nprivate MessageService messageService;\n\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\"><strong>Naming the Field:<\/strong><\/h3>\n\n\n\n<p>If you don&#8217;t want to use the @Qualifier annotation explicitly, you can name the field with the same name as the bean definition:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\n@Service(&quot;smsService&quot;)\npublic class SmsMessageService implements MessageService {\n    \/\/ some code here\n}\n\n@Service\npublic class ForgetPasswordService {\n\n    private final MessageService smsService;\n\n    @Autowired\n    public ForgetPasswordService(MessageService smsService) {\n        this.smsService = smsService;\n    }\n}\n\n\n<\/pre><\/div>\n\n\n<p>It\u2019s important to remember that using this method, your field name is coupled with the qualifier name you defined, if you change the qualifier name or the field name, it might break everything. So use it with caution.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Defining Beans in Configuration Classes:<\/strong><\/h3>\n\n\n\n<p>If you have a configuration class like this, you can define the bean qualifier name in the @Bean annotation.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\n@Configuration\npublic class QualifierConfig {\n\n    @Bean(&quot;beanDefinition&quot;)\n    public BeanDefinition beanDefinition() {\n        return new BeanDefinition();\n    }\n}\n\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>Have you already faced a problem like this in your project? Did you use the @Qualifier? Have you seen this annotation in your daily job? Let me know in the comments, or on social media!<\/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>When working on a Spring project, you might encounter a situation where you have multiple bean implementations for the same type. This can cause an error because Spring doesn&#8217;t know which bean to inject. To solve this, we use the @Qualifier annotation. The Problem Let&#8217;s say you have an interface MessageService that your application uses [&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,26],"class_list":["post-214","post","type-post","status-publish","format-standard","hentry","category-spring","tag-java","tag-programming","tag-software-development","tag-spring-boot","tag-spring-framework","tag-technology"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=\/wp\/v2\/posts\/214","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=214"}],"version-history":[{"count":0,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=\/wp\/v2\/posts\/214\/revisions"}],"wp:attachment":[{"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=214"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=214"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=214"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}