Spring setter injection not mandatory





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I read that There is no guarantee in a setter injection that the dependency will be injected as opposed to constructor injection that the dependency is mandatory.



I really don't understand that point. If I write the following method:



@Autowired
public void setMyBean(MyBean otherBean){
this.otherBean = otherBean;
}


what does it mean that otherBean won't be injected?










share|improve this question


















  • 4





    where did you read that ?

    – Ken Chan
    Jan 4 at 5:12













  • So why we need the required flag for? Autowired(required=false) ? by default it is true and spring will fail to load the application if no bean found during injection.

    – Lyju I Edwinson
    Jan 4 at 5:20


















1















I read that There is no guarantee in a setter injection that the dependency will be injected as opposed to constructor injection that the dependency is mandatory.



I really don't understand that point. If I write the following method:



@Autowired
public void setMyBean(MyBean otherBean){
this.otherBean = otherBean;
}


what does it mean that otherBean won't be injected?










share|improve this question


















  • 4





    where did you read that ?

    – Ken Chan
    Jan 4 at 5:12













  • So why we need the required flag for? Autowired(required=false) ? by default it is true and spring will fail to load the application if no bean found during injection.

    – Lyju I Edwinson
    Jan 4 at 5:20














1












1








1


1






I read that There is no guarantee in a setter injection that the dependency will be injected as opposed to constructor injection that the dependency is mandatory.



I really don't understand that point. If I write the following method:



@Autowired
public void setMyBean(MyBean otherBean){
this.otherBean = otherBean;
}


what does it mean that otherBean won't be injected?










share|improve this question














I read that There is no guarantee in a setter injection that the dependency will be injected as opposed to constructor injection that the dependency is mandatory.



I really don't understand that point. If I write the following method:



@Autowired
public void setMyBean(MyBean otherBean){
this.otherBean = otherBean;
}


what does it mean that otherBean won't be injected?







java spring






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 4 at 5:07









user1409534user1409534

77111124




77111124








  • 4





    where did you read that ?

    – Ken Chan
    Jan 4 at 5:12













  • So why we need the required flag for? Autowired(required=false) ? by default it is true and spring will fail to load the application if no bean found during injection.

    – Lyju I Edwinson
    Jan 4 at 5:20














  • 4





    where did you read that ?

    – Ken Chan
    Jan 4 at 5:12













  • So why we need the required flag for? Autowired(required=false) ? by default it is true and spring will fail to load the application if no bean found during injection.

    – Lyju I Edwinson
    Jan 4 at 5:20








4




4





where did you read that ?

– Ken Chan
Jan 4 at 5:12







where did you read that ?

– Ken Chan
Jan 4 at 5:12















So why we need the required flag for? Autowired(required=false) ? by default it is true and spring will fail to load the application if no bean found during injection.

– Lyju I Edwinson
Jan 4 at 5:20





So why we need the required flag for? Autowired(required=false) ? by default it is true and spring will fail to load the application if no bean found during injection.

– Lyju I Edwinson
Jan 4 at 5:20












3 Answers
3






active

oldest

votes


















0














DI exists in two major variants: Constructor-based dependency injection and Setter-based dependency injection.



Constructor-based Dependency Injection



Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency.



Setter-based Dependency Injection



Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or a no-argument static factory method to instantiate your bean.



Again, constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state (not having passed its collaborators). In other words, when using constructor injection you do not have to use a dedicated mechanism to ensure required properties are set (other than normal Java mechanisms).



But in setter based injection if the dependencies is not found the object is created, but the dependent object will be null. Means, setter injection does not ensures dependency Injection. You can find a detailed article here.



Note that use of the @Required annotation on a setter method can be used to make the property be a required dependency.






share|improve this answer































    0














    if you are using setter based injection in your bean then your bean will initialise no matter all dependencies have been resolved or not, but you will get NPE when try to use these non resolved/initialised dependencies in your code.
    But in Constructor based injection your bean will initialise once all dependencies have been resolved.






    share|improve this answer































      0














      Whenever we use @Autowired, Spring makes sure the relevant bean exists and gets injected for use.
      If this cannot be done, Spring throws an exception and the application fails to start.


      The statement actually is in reference to testing your code. By this I mean, If using setter based dependency injection it may be possible that one will forget to inject the required bean and the corresponding test cases might fail.

      constructor based dependency injection ensures that one has to init all required beans before actually using the required code.


      You can read it in detail over here






      share|improve this answer
























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54033367%2fspring-setter-injection-not-mandatory%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        DI exists in two major variants: Constructor-based dependency injection and Setter-based dependency injection.



        Constructor-based Dependency Injection



        Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency.



        Setter-based Dependency Injection



        Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or a no-argument static factory method to instantiate your bean.



        Again, constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state (not having passed its collaborators). In other words, when using constructor injection you do not have to use a dedicated mechanism to ensure required properties are set (other than normal Java mechanisms).



        But in setter based injection if the dependencies is not found the object is created, but the dependent object will be null. Means, setter injection does not ensures dependency Injection. You can find a detailed article here.



        Note that use of the @Required annotation on a setter method can be used to make the property be a required dependency.






        share|improve this answer




























          0














          DI exists in two major variants: Constructor-based dependency injection and Setter-based dependency injection.



          Constructor-based Dependency Injection



          Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency.



          Setter-based Dependency Injection



          Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or a no-argument static factory method to instantiate your bean.



          Again, constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state (not having passed its collaborators). In other words, when using constructor injection you do not have to use a dedicated mechanism to ensure required properties are set (other than normal Java mechanisms).



          But in setter based injection if the dependencies is not found the object is created, but the dependent object will be null. Means, setter injection does not ensures dependency Injection. You can find a detailed article here.



          Note that use of the @Required annotation on a setter method can be used to make the property be a required dependency.






          share|improve this answer


























            0












            0








            0







            DI exists in two major variants: Constructor-based dependency injection and Setter-based dependency injection.



            Constructor-based Dependency Injection



            Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency.



            Setter-based Dependency Injection



            Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or a no-argument static factory method to instantiate your bean.



            Again, constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state (not having passed its collaborators). In other words, when using constructor injection you do not have to use a dedicated mechanism to ensure required properties are set (other than normal Java mechanisms).



            But in setter based injection if the dependencies is not found the object is created, but the dependent object will be null. Means, setter injection does not ensures dependency Injection. You can find a detailed article here.



            Note that use of the @Required annotation on a setter method can be used to make the property be a required dependency.






            share|improve this answer













            DI exists in two major variants: Constructor-based dependency injection and Setter-based dependency injection.



            Constructor-based Dependency Injection



            Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency.



            Setter-based Dependency Injection



            Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or a no-argument static factory method to instantiate your bean.



            Again, constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state (not having passed its collaborators). In other words, when using constructor injection you do not have to use a dedicated mechanism to ensure required properties are set (other than normal Java mechanisms).



            But in setter based injection if the dependencies is not found the object is created, but the dependent object will be null. Means, setter injection does not ensures dependency Injection. You can find a detailed article here.



            Note that use of the @Required annotation on a setter method can be used to make the property be a required dependency.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 4 at 7:02









            ShaheerShaheer

            848914




            848914

























                0














                if you are using setter based injection in your bean then your bean will initialise no matter all dependencies have been resolved or not, but you will get NPE when try to use these non resolved/initialised dependencies in your code.
                But in Constructor based injection your bean will initialise once all dependencies have been resolved.






                share|improve this answer




























                  0














                  if you are using setter based injection in your bean then your bean will initialise no matter all dependencies have been resolved or not, but you will get NPE when try to use these non resolved/initialised dependencies in your code.
                  But in Constructor based injection your bean will initialise once all dependencies have been resolved.






                  share|improve this answer


























                    0












                    0








                    0







                    if you are using setter based injection in your bean then your bean will initialise no matter all dependencies have been resolved or not, but you will get NPE when try to use these non resolved/initialised dependencies in your code.
                    But in Constructor based injection your bean will initialise once all dependencies have been resolved.






                    share|improve this answer













                    if you are using setter based injection in your bean then your bean will initialise no matter all dependencies have been resolved or not, but you will get NPE when try to use these non resolved/initialised dependencies in your code.
                    But in Constructor based injection your bean will initialise once all dependencies have been resolved.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 4 at 7:26









                    DevendraDevendra

                    1199




                    1199























                        0














                        Whenever we use @Autowired, Spring makes sure the relevant bean exists and gets injected for use.
                        If this cannot be done, Spring throws an exception and the application fails to start.


                        The statement actually is in reference to testing your code. By this I mean, If using setter based dependency injection it may be possible that one will forget to inject the required bean and the corresponding test cases might fail.

                        constructor based dependency injection ensures that one has to init all required beans before actually using the required code.


                        You can read it in detail over here






                        share|improve this answer




























                          0














                          Whenever we use @Autowired, Spring makes sure the relevant bean exists and gets injected for use.
                          If this cannot be done, Spring throws an exception and the application fails to start.


                          The statement actually is in reference to testing your code. By this I mean, If using setter based dependency injection it may be possible that one will forget to inject the required bean and the corresponding test cases might fail.

                          constructor based dependency injection ensures that one has to init all required beans before actually using the required code.


                          You can read it in detail over here






                          share|improve this answer


























                            0












                            0








                            0







                            Whenever we use @Autowired, Spring makes sure the relevant bean exists and gets injected for use.
                            If this cannot be done, Spring throws an exception and the application fails to start.


                            The statement actually is in reference to testing your code. By this I mean, If using setter based dependency injection it may be possible that one will forget to inject the required bean and the corresponding test cases might fail.

                            constructor based dependency injection ensures that one has to init all required beans before actually using the required code.


                            You can read it in detail over here






                            share|improve this answer













                            Whenever we use @Autowired, Spring makes sure the relevant bean exists and gets injected for use.
                            If this cannot be done, Spring throws an exception and the application fails to start.


                            The statement actually is in reference to testing your code. By this I mean, If using setter based dependency injection it may be possible that one will forget to inject the required bean and the corresponding test cases might fail.

                            constructor based dependency injection ensures that one has to init all required beans before actually using the required code.


                            You can read it in detail over here







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 4 at 8:10









                            swayamrainaswayamraina

                            875813




                            875813






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54033367%2fspring-setter-injection-not-mandatory%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Monofisismo

                                Angular Downloading a file using contenturl with Basic Authentication

                                Olmecas