{"id":202,"date":"2024-06-10T21:53:46","date_gmt":"2024-06-11T00:53:46","guid":{"rendered":"https:\/\/springmasteryhub.com\/?p=202"},"modified":"2024-06-10T21:53:46","modified_gmt":"2024-06-11T00:53:46","slug":"understanding-autowired-in-spring-a-comprehensive-guide","status":"publish","type":"post","link":"https:\/\/springmasteryhub.com\/?p=202","title":{"rendered":"Understanding @Autowired in Spring: A Comprehensive Guide"},"content":{"rendered":"\n<h1 class=\"wp-block-heading\">Introduction<\/h1>\n\n\n\n<p>The <code>@Autowired<\/code> annotation is one of the most common annotations when working with Spring. Its objective is simple: to tell Spring to inject a dependency bean into our beans. In other words, it will pick an instance of a bean from the Spring IoC (Inversion of Control) container and set it into our components. This will be done at the start of the Spring application when it initializes and configures all the beans.<\/p>\n\n\n\n<p>Let\u2019s see examples of how to work with this annotation:<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">1. Field Injection<\/h2>\n\n\n\n<p>The annotation is placed on the field. Spring will automatically locate and inject the correct bean implementation into it.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\n@Service\npublic class CustomerService {\n\n    @Autowired\n    private CustomerRepository customerRepository;\n\n}\n\n\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">2. Setter Injection<\/h2>\n\n\n\n<p>Spring will use the set method to inject the correct bean implementation.<\/p>\n\n\n\n<p>Example:<\/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 static final Logger log = LoggerFactory.getLogger(OrderService.class);\n    private ProductCatalog productCatalog;\n\n    @Autowired\n    public void setProductCatalog(ProductCatalog productCatalog) {\n        log.info(&quot;Injecting by set&quot;);\n        this.productCatalog = productCatalog;\n    }\n}\n\n\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">3. Constructor Injection<\/h2>\n\n\n\n<p>You can inject the beans using the constructor. Spring will use the constructor arguments to inject the beans.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\n@Service\npublic class BillingService {\n\n    private final InvoiceGenerator invoiceGenerator;\n\n    @Autowired\n    public BillingService(InvoiceGenerator invoiceGenerator) {\n        this.invoiceGenerator = invoiceGenerator;\n    }\n}\n\n\n<\/pre><\/div>\n\n\n<p>Since Spring Framework 4.3, the annotation in the constructor is no longer necessary. This will work in beans with a single constructor.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\n@Service\npublic class ReportService {\n\n    private ReportGenerator reportGenerator;\n\n    public ReportService(ReportGenerator reportGenerator) {\n        this.reportGenerator = reportGenerator;\n    }\n}\n\n\n<\/pre><\/div>\n\n\n<p>If your bean defines multiple constructors and has the default empty constructor, Spring will pick the default to create the bean.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\n@Service\npublic class NotificationService {\n\n    private static final Logger log = LoggerFactory.getLogger(NotificationService.class);\n    private EmailSender emailSender;\n    private SmsSender smsSender;\n\n    public NotificationService() {\n\t\t    log.info(&quot;Spring will pick this one&quot;);\n    }\n\n    public NotificationService(EmailSender emailSender) {\n        log.info(&quot;Injecting email sender&quot;);\n        this.emailSender = emailSender;\n    }\n\n    public NotificationService(EmailSender emailSender, SmsSender smsSender) {\n        log.info(&quot;Injecting both&quot;);\n        this.emailSender = emailSender;\n        this.smsSender = smsSender;\n    }\n}\n\n\n<\/pre><\/div>\n\n\n<p>If you only have constructors with fields, you must annotate one with <code>@Autowired<\/code> so Spring can locate and inject the beans.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\n@Service\npublic class NotificationService {\n\n    private static final Logger log = LoggerFactory.getLogger(NotificationService.class);\n    private EmailSender emailSender;\n    private SmsSender smsSender;\n\n    public NotificationService(EmailSender emailSender) {\n        this.emailSender = emailSender;\n    }\n\n    @Autowired\n    public NotificationService(EmailSender emailSender, SmsSender smsSender) {\n        log.info(&quot;Spring will inject this one&quot;);\n        this.emailSender = emailSender;\n        this.smsSender = smsSender;\n    }\n}\n\n\n<\/pre><\/div>\n\n\n<p>Otherwise, Spring will throw a <code>BeanInstantiationException<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">4. Marking as Not Required<\/h2>\n\n\n\n<p>By default, the fields annotated with <code>@Autowired<\/code> are required. If Spring does not find any instance of the correct bean to inject, it will fail to launch.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\n@Service\npublic class MandatoryService {\n\n    @Autowired\n    private OptionalBean mandatoryBean;\n\n}\n\n\/\/ Not defined as a bean\npublic class OptionalBean {\n}\n\n\n<\/pre><\/div>\n\n\n<p>Spring will tell you at the start of the application:<\/p>\n\n\n\n<p><code>Field mandatoryBean in com.spring.mastery.autowired.MandatoryService required a bean of type 'com.spring.mastery.autowired.OptionalBean' that could not be found.<\/code><\/p>\n\n\n\n<p>But it will start if you set the property as required <code>false<\/code>.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\n@Service\npublic class MandatoryService {\n\n    @Autowired(required = false)\n    private OptionalBean mandatoryBean;\n\n}\n\n\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Now you understand all your options when using <code>@Autowired<\/code> in your project!<\/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\n\n\n<h3 class=\"wp-block-heading\">References<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/docs.spring.io\/spring-framework\/reference\/core\/beans\/annotation-config\/autowired.html\" rel=\"nofollow\">Spring Documentation on @Autowired<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.baeldung.com\/spring-autowire\" rel=\"nofollow\">Baeldung on Spring Autowired<\/a><\/li>\n<\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction The @Autowired annotation is one of the most common annotations when working with Spring. Its objective is simple: to tell Spring to inject a dependency bean into our beans. In other words, it will pick an instance of a bean from the Spring IoC (Inversion of Control) container and set it into our components. [&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,22,23,26],"class_list":["post-202","post","type-post","status-publish","format-standard","hentry","category-spring","tag-java","tag-programming","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\/202","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=202"}],"version-history":[{"count":0,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=\/wp\/v2\/posts\/202\/revisions"}],"wp:attachment":[{"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=202"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=202"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=202"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}