{"id":182,"date":"2024-06-03T22:24:31","date_gmt":"2024-06-04T01:24:31","guid":{"rendered":"https:\/\/springmasteryhub.com\/?p=182"},"modified":"2024-06-03T22:24:31","modified_gmt":"2024-06-04T01:24:31","slug":"simplifying-dependency-management-with-spring-ioc","status":"publish","type":"post","link":"https:\/\/springmasteryhub.com\/?p=182","title":{"rendered":"Simplifying Dependency Management with Spring IoC"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Introduction<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Imagine writing an application where you have to create and manage connections with your database system, use Kafka, set up a web server, configure a cache system, and handle JSON serialization and deserialization, among many other components. The amount of work required just to set up these dependencies before starting to develop features that bring real value can be overwhelming. Moreover, maintaining and setting these dependencies across all components of your code can be cumbersome.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the past, many developers dealt with this by employing various design patterns such as Factories, Builders, Proxies, Service Locators, reflection, and many other methods. While these helped, components often became tightly coupled and overly knowledgeable about their dependencies.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Traditional Factory Method<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example of a factory method to deal with dependency creation without Spring:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic class PaymentProcessorFactory {\n\n    public static PaymentProcessor createService(String type) {\n        if (type.equalsIgnoreCase(&quot;paypal&quot;)) {\n            return new PayPalPaymentProcessor();\n        } else if (type.equalsIgnoreCase(&quot;stripe&quot;)) {\n            return new StripePaymentProcessor();\n        } else {\n            throw new IllegalArgumentException(&quot;Invalid payment processor type: &quot; + type);\n        }\n    }\n}\n\n\/\/ Usage\nPaymentProcessor paypalProcessor = PaymentProcessorFactory.createService(&quot;paypal&quot;);\nPaymentProcessor stripeProcessor = PaymentProcessorFactory.createService(&quot;stripe&quot;);\n\n\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">While this method works, it has limitations. Adding more methods requires changing the code, which makes it tightly coupled and hard to maintain.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introducing Spring IoC<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To address these issues, Spring introduced the Spring IoC (Inversion of Control) container, which is part of the Spring application context.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Configuration\npublic class PaymentProcessorConfig {\n\n    @Bean\n    @ConditionalOnProperty(prefix = &quot;payment&quot;, name = &quot;processor&quot;, havingValue = &quot;stripe&quot;)\n    public PaymentProcessor stripePaymentProcessor() {\n        return new StripePaymentProcessor();\n    }\n\n    @Bean\n    @ConditionalOnProperty(prefix = &quot;payment&quot;, name = &quot;processor&quot;, havingValue = &quot;paypal&quot;)\n    public PaymentProcessor paypalPaymentProcessor() {\n        return new PayPalPaymentProcessor();\n    }\n}\n\n\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Understanding IoC<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Each component is a bean. A bean can be an infrastructure bean (like repositories for interacting with databases, Kafka templates for sending messages) or components created by developers to support business rules.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">IoC means Inversion of Control. Instead of a component calling a factory for a Kafka template to send messages, Spring handles this and delivers a fully functional bean to the component. The component no longer needs to know where the bean comes from or how it\u2019s created. It follows the pattern of \u201cdon\u2019t call me, we\u2019ll call you.\u201d The control of those dependencies is no longer handled by the component but managed by Spring IoC.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This approach reduces coupling and makes it easier to connect application components, making the application more reusable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Spring IoC in Action<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Spring IoC reads your components and configurations (which can be in XML or Java annotations) and provides a ready-to-go application so the developer can start right away focusing on features that bring more value. It creates all beans at runtime when the application starts.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Spring IoC uses your configurations to set up your beans through properties, providing flexibility over the beans. For example, when setting the payment processor to Stripe:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n\npayment.processor=stripe\n\n\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">This can be easily changed to PayPal without touching a single line of your application component that calls this dependency.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Simplified Dependency Usage<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Using these dependencies becomes straightforward:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Component\npublic class CheckoutService {\n\n    @Autowired\n    private PaymentProcessor paymentProcessor;\n\n    public void processCheckout(PaymentDetails details) {\n        paymentProcessor.processPayment(details);\n    }\n}\n\n\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Flexibility and Productivity<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Depending on the changes in your configuration properties (if it does not involve infrastructure changes like changing your database driver), you may not need to recompile and restart your application. Spring can reload the configurations while the application is running.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Spring IoC makes our lives easier, our applications less coupled and more reusable, and enhances productivity by allowing developers to focus on what matters most.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you like Spring make sure to follow me and stay tuned to learn more! Don\u2019t miss out!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/twitter.com\/WillianFMoya\">Willian Moya (@WillianFMoya) \/ X (twitter.com)<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/www.linkedin.com\/in\/willianmoya\/\">Willian Ferreira Moya | LinkedIn<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Developers faced challenges with setting up complex dependencies and managing them across all components. Traditional methods like the Factory Method proved limiting and tightly coupled. Spring introduced IoC to address these issues, reducing coupling, making components more reusable, and allowing focus on value-driven features. Spring IoC facilitates simplified dependency usage and enhances productivity.<\/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,20,22,23],"class_list":["post-182","post","type-post","status-publish","format-standard","hentry","category-spring","tag-java","tag-software-development","tag-spring-boot","tag-spring-framework"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=\/wp\/v2\/posts\/182","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=182"}],"version-history":[{"count":0,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=\/wp\/v2\/posts\/182\/revisions"}],"wp:attachment":[{"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=182"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=182"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=182"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}