Spring Constructor Injection: Why is it the recommended approach to Dependency Injection?

แชร์
ฝัง
  • เผยแพร่เมื่อ 2 มี.ค. 2022
  • In this tutorial, you will learn why Constructor Injection is the recommended approach to dependency injection in Spring. To accomplish this you will learn some of the basics around Spring Beans, Application Context, Dependency (DI) Injection, and Inversion of Control (IoC).
    👋🏻Connect with me:
    Website: www.danvega.dev
    Twitter: / therealdanvega
    Github: github.com/danvega
    LinkedIn: / danvega
    Newsletter: www.danvega.dev/newsletter
    SUBSCRIBE TO MY CHANNEL: bit.ly/2re4GH0 ❤️
  • วิทยาศาสตร์และเทคโนโลยี

ความคิดเห็น • 119

  • @welltv1142
    @welltv1142 2 ปีที่แล้ว +49

    Finally someone digging more into theory. Often times Spring boot tutorials just telling you how to do it but not why. This is the first video I really find helpful, keep up the good work! Greetings from Germany.

    • @DanVega
      @DanVega  ปีที่แล้ว +2

      Hello Germany 👋🏻 Thank you for the kind words. I'm glad you enjoyed the explanation.

    • @maksadnahibhoolna-wc2ef
      @maksadnahibhoolna-wc2ef ปีที่แล้ว

      @@DanVega What's the difference between these two ways you are instantiating the object of VideoRepository at following timestamps :
      The way you have instantiated repository object at 15:20
      v/s
      The way you have instantiated repository object (using constructor DI) at 18:08
      @DanVega I was little confused since whether the code of former timestamp also a constructor based dependency Injection ?

    • @leoMC4384
      @leoMC4384 ปีที่แล้ว

      You're right. I've seen a couple of tutotials and they say: "You have to implement dependency injection, otherwise you'll get an exception". And the Spring Framework itself tells you to use a Bean for some class. But I'm wondering: Why do we have to do all this??? Here it is. BTW, my brother lives in Germany. :)

  • @aparnaguru8047
    @aparnaguru8047 8 หลายเดือนก่อน +3

    I searched a lot to understand why we are using certain stuffs in spring and I could only find it here.. everywhere it is just how to do and not why to do.. thank you so much

    • @DanVega
      @DanVega  8 หลายเดือนก่อน

      Thank you, I'm glad I am able to bring a different perspective and help out!

  • @kamalhm-dev
    @kamalhm-dev 2 ปีที่แล้ว +18

    definitely learned a lot Dan! I’ve never seen test with autowired annotations. Usually its all using Mock annotations, please do a continuation of this on how to properly test that controller with constructor injection

  • @pinoyboi4563
    @pinoyboi4563 2 ปีที่แล้ว +14

    Finally a high quality Spring tutorial!
    can't wait to see more 🔥 this was so clear glad I found you

    • @DanVega
      @DanVega  2 ปีที่แล้ว +1

      Thank you so much for the kind words!

  • @shortestpath
    @shortestpath 2 ปีที่แล้ว +7

    Great video. All topics (beans, application context, injection, ioc) just happen to hit on many things I've been wondering about lately, considering myself still fairly new to Spring. Especially loved the clear explanations on the different kinds of injection, and WHY we want to favor constructor injection.

    • @DanVega
      @DanVega  2 ปีที่แล้ว

      Thank you for the kind words, glad you enjoyed it!

  • @iirayan7
    @iirayan7 5 หลายเดือนก่อน +1

    It's All about why we use it and then it will be more clear and make scenes. Thank You a lot. Thumbs up for you.

  • @AleksandarT10
    @AleksandarT10 2 ปีที่แล้ว +5

    Great Video Dan!
    Found the channel via Spring Boot 2.6 video.
    We need more videos like this one that explain Spring concepts in a practical manner - i am sure that many people are using Spring for many years but are still not aware why some things work like they do and why some choices have been made in the framework.
    Anyway i had to learn this the hard way, in almost all of the projects we are using Field Injection, but there was use case when some specific functionality had to be tested and mocking was not an option, so i learned that "constructor" injection is the only way to do it properly.
    Keep up the good work!

    • @DanVega
      @DanVega  2 ปีที่แล้ว +1

      Thank you for the kind words and for taking the time to provide some feedback. It is very much appreciated.

  • @OmarMendozaKS
    @OmarMendozaKS ปีที่แล้ว +2

    I was using a lot of that stuff and had kind of an idea of why I was using it but your take is super simple, thank you, it was an incredible back to the basics

    • @DanVega
      @DanVega  ปีที่แล้ว

      Glad this was helpful.

  • @dimosthenis_dev
    @dimosthenis_dev ปีที่แล้ว +1

    Took me about 2 hours to follow along taking notes and looking up definitions I didn't know, but man am I glad I did! I feel as though I have a solid base level understanding of Spring concepts after the video. Totally recommend this to everyone, your every sentence speaks volumes of your knowledge. Thank you and keep it up!

  • @fabriciotakaki5357
    @fabriciotakaki5357 2 ปีที่แล้ว +3

    really good content! i always made constructor injection cause my lead told me to, but i never knew why. Thank you!

  • @MCjusticejuice
    @MCjusticejuice 2 ปีที่แล้ว +4

    If you prefer the cleaner look of field injection, but don't want to give up the advantages of constructor injection, there is a way. Just declare the dependency final and use the Lombok annotation RequiredArgsConstructor on your class definition. Hope this helps someone.

    • @dd1.d
      @dd1.d 2 ปีที่แล้ว

      Yes, I usually do this

    • @RAHUL-xy1ds
      @RAHUL-xy1ds ปีที่แล้ว

      So are you doing that so that the dependency is never null?I could not understand the point he made about the possibility that your dependency could be null if you use field injection

    • @MCjusticejuice
      @MCjusticejuice ปีที่แล้ว

      @@RAHUL-xy1ds Because you can't use field injection with final declared instance variables. This leads to a mutable field, which could also be changed to null. It's more or less an academical issue, but you can never guarantee that the injected field stays unchanged. With constructor injection instead, you can declare the field as final. This ensures that this field is immutable and can only be set once inside a constructor.

    • @RAHUL-xy1ds
      @RAHUL-xy1ds ปีที่แล้ว +1

      @@MCjusticejuice Oh alright...thank you so much...

  • @thecodeninjaeu
    @thecodeninjaeu 2 หลายเดือนก่อน

    How am I just finding about your content now?😭 your channel is a goldmine

  • @Soromeister
    @Soromeister 2 ปีที่แล้ว

    Clear explanation of not only Constructor Injection, but also Dependency Injection in general.

  • @collindewitt1989
    @collindewitt1989 2 ปีที่แล้ว +3

    Hi Dan, this is a great video, I have been a Spring dev for years, but this is such a nice clear explination. Really enjoying these videos that take small aspects of spring and expalined so well. Thank you

    • @DanVega
      @DanVega  2 ปีที่แล้ว

      Glad you enjoyed it!

  • @asherkhan2656
    @asherkhan2656 7 หลายเดือนก่อน

    Discovered you recently Dan and I must say I am glad I did. I have subscribed and started watching some of your videos to help reinforce some of my understanding on things I picked up while working with Spring boot but not necessarily clear on everything. Very helpful sir...keep up the great work !! Greetings from Texas :)

  • @asterixcode
    @asterixcode 2 ปีที่แล้ว

    Great video, thanks for your dedicated work to teach relevant and in-depth spring knowledge. We appreciate it!

    • @DanVega
      @DanVega  2 ปีที่แล้ว

      Thank you for the kind words. I appreciate it 😊

  • @DarkHid3
    @DarkHid3 5 หลายเดือนก่อน

    I really like the way you explain all these things, you are explaining everything very well and simple! Good video!

  • @raghavanaliassaravananm1546
    @raghavanaliassaravananm1546 ปีที่แล้ว +1

    A nice set of videos Dan. I really like the precursory problem statement you share in the beginning few seconds of the video, then you go with your short, self intro and then stepping into the full video. Unique style and I like the way you present the stuff. Though I am a subscriber of your newsletter and the TH-cam channel, I am now watching all the videos of yours one by one now :) Keep rocking and thank you for all the knowledge you share!

    • @DanVega
      @DanVega  ปีที่แล้ว +1

      Wow thank you so much for the kind words my friend.

  • @mariohernandez6590
    @mariohernandez6590 ปีที่แล้ว

    This is exactly I was looking for as a dotnet developer switching over to Kotlin + spring. All the other tutorials didn’t explain how things were working under the hood. Cheers!

  • @yousseflotfi904
    @yousseflotfi904 2 ปีที่แล้ว +1

    simple and clean explanation, thank you so much, now I can say that I understand what is DI ,IOC

  • @inzi27
    @inzi27 ปีที่แล้ว

    Happy that I stumbled upon your channel Dan. you are super awesome 😎👍🏼

  • @andrezanlorensi
    @andrezanlorensi ปีที่แล้ว

    Your tutorial was so helpful to me, i definitely learned it. Thanks a lot

  • @dereklorimer1914
    @dereklorimer1914 2 ปีที่แล้ว +1

    Thanks. Great tutorial

  • @user-iz2je9zm4c
    @user-iz2je9zm4c 2 ปีที่แล้ว

    really clear to understand.
    thanks Dan! 😀

  • @fadygamilmahrousmasoud5863
    @fadygamilmahrousmasoud5863 ปีที่แล้ว

    very interesting and really clear explanation of why we use these concepts .. thank you :D

  • @grrlgd3835
    @grrlgd3835 2 ปีที่แล้ว

    great stuff...again and again. keep it up Dan

  • @abeard1
    @abeard1 2 ปีที่แล้ว +1

    Very nice explanation! Spring internals are super interesting

    • @DanVega
      @DanVega  2 ปีที่แล้ว +1

      Thank you!

  • @centfox
    @centfox ปีที่แล้ว

    Really great!!! Thank you.

  • @samuelakuma1174
    @samuelakuma1174 ปีที่แล้ว

    Thank you Dan!

  • @dosinadasung7981
    @dosinadasung7981 2 ปีที่แล้ว +1

    Now I understand DI and IOC

  • @shashikantverma3215
    @shashikantverma3215 ปีที่แล้ว

    Thanks for the easy explanation

  • @serengetysson3159
    @serengetysson3159 ปีที่แล้ว

    Great tutorial.. great explanation!

  • @cpthermes3703
    @cpthermes3703 ปีที่แล้ว

    Very informative, love your channel. Keep it up

  • @anutoshghosh7893
    @anutoshghosh7893 ปีที่แล้ว

    extremely helpful!! thanks!!

  • @nayeemrafsan356
    @nayeemrafsan356 ปีที่แล้ว

    loved the explanation

  • @badripaudel77
    @badripaudel77 9 หลายเดือนก่อน

    Couldn't stop commenting. Lucid explanations ❤

    • @DanVega
      @DanVega  9 หลายเดือนก่อน

      Glad you enjoyed it 🤩

  • @utkarshkumar8613
    @utkarshkumar8613 29 วันที่ผ่านมา

    Great explanation!!

  • @unus55
    @unus55 3 หลายเดือนก่อน

    Thanks Dan.
    Nice content

  • @centfox
    @centfox ปีที่แล้ว

    Really great!! Thank you. :)

  • @michelchaghoury870
    @michelchaghoury870 2 ปีที่แล้ว

    Mannnn so useful please keep going we need more content like these, and please some docker and kubernetes with spring tutorials would be great

    • @DanVega
      @DanVega  2 ปีที่แล้ว +1

      Thanks Michel, appreciate the continued support and feedback.

  • @sachinmankotia2291
    @sachinmankotia2291 2 ปีที่แล้ว

    wonderful explanation. I was looking for such explanation for a long time :)

    • @DanVega
      @DanVega  ปีที่แล้ว

      Thank you Sachin. Glad it helped you out!

  • @jackdanyal4329
    @jackdanyal4329 2 ปีที่แล้ว +1

    Junior and some middle devs mostly cares about the count of code lines and think less == good. Senior and lead devs cares about code quality, readability and security and don't care about lines of code :)

  • @sanquinteros
    @sanquinteros ปีที่แล้ว

    Video was incredible Dan, thanks for making such an effort on explaining all the little details. A recommendation I have is to use the same microphone while talking in-front of the camera as the one you are using when writting code (the second microphone is way better quality in my opinion), because the difference between them is very clear and could irritate some viewers slightly.

  • @enesb4797
    @enesb4797 5 หลายเดือนก่อน +1

    perfection!

  • @HighlifeC
    @HighlifeC 11 หลายเดือนก่อน

    This is gold... revised before an interview...lol

  • @user-vq5eb3sm4p
    @user-vq5eb3sm4p ปีที่แล้ว

    thanks , great examples :D

  • @camilazucchis
    @camilazucchis 29 วันที่ผ่านมา

    thank you so much!

  • @poojapatole3573
    @poojapatole3573 8 หลายเดือนก่อน

    Loved it

  • @ianperfitt
    @ianperfitt ปีที่แล้ว

    thank you!

  • @aneuryperez
    @aneuryperez ปีที่แล้ว

    Great Content.

  • @raymondyoo5461
    @raymondyoo5461 10 หลายเดือนก่อน

    Great talk 👍👍
    It became much clearer why I should create classes that way
    Thanks a lot

    • @DanVega
      @DanVega  10 หลายเดือนก่อน +1

      Glad to hear that

  • @hadisoleimany6271
    @hadisoleimany6271 2 ปีที่แล้ว +1

    Thank you, it was a good video, actually, I learned about why the Constructor injection is better

  • @michaellebediev6715
    @michaellebediev6715 ปีที่แล้ว +1

    Thanks a lot!

    • @DanVega
      @DanVega  ปีที่แล้ว

      You're welcome!

  • @Airforce_inter
    @Airforce_inter 3 หลายเดือนก่อน

    great keep making such useful and code based videos bro, tnx

    • @DanVega
      @DanVega  3 หลายเดือนก่อน

      You are welcome

  • @johncerpa3782
    @johncerpa3782 2 ปีที่แล้ว

    Great explanation

    • @DanVega
      @DanVega  2 ปีที่แล้ว

      Glad it was helpful!

  • @vitaliiplagov
    @vitaliiplagov 2 ปีที่แล้ว

    Thanks for the video. A very simple and easy explanation of a concept that I thought is quite difficult. Turns out, it's not!

    • @DanVega
      @DanVega  ปีที่แล้ว

      Yes! So glad that it helped clear up this topic for you Vitali

  • @hippiestafarii
    @hippiestafarii 2 ปีที่แล้ว

    The better way to learn is to understand thank you :-)

  • @vern0312
    @vern0312 2 ปีที่แล้ว +1

    An interviewer asked me this question and my answer was "idk it's just how I was taught 😎" . I didn't get the job 🤣🤣. So this video is appreciated.

    • @DanVega
      @DanVega  2 ปีที่แล้ว +3

      Sorry to hear you didn't get the job, hope it all worked out for the best. I have been in the same position. I take those as learning opportunities for the next one.

    • @vern0312
      @vern0312 2 ปีที่แล้ว +1

      @@DanVega absolutely, thanks again Dan.

  • @mohammedabraruddin9779
    @mohammedabraruddin9779 2 ปีที่แล้ว

    This is the first perfect answer

  • @returncode0000
    @returncode0000 2 ปีที่แล้ว

    Your videos on a level that explains things so well, great stuff, as always 👍Keep up the good work, you're helping me so much! Great content, as always, so clear and well structured, Dan is the best instructor ever! Deep dive 27:41 please 😊
    This video justcame up the right time. I always have some problems understanding how to connect beans the right way, also with JPA or other frameworks, maybe mixed with streams/collections and debugging(!) them correctly.
    Questions:
    - at 10:55 - why does Sping identifies the bean with lower Case? Is it only for creating a unique identifier/name internally or is there another reason?
    - What theme you use for IntelliJ?

    • @raghavanaliassaravananm1546
      @raghavanaliassaravananm1546 ปีที่แล้ว +1

      Guess he had explained it along the way that Spring Framework uses the camelCase notation for the Beans.

  • @AnanyDwivedi-si1mz
    @AnanyDwivedi-si1mz 4 หลายเดือนก่อน

    Thank you very much for the cool explanation; is there a way to use constructor injection when there are more than one dependencies

  • @G12ghbas
    @G12ghbas 4 หลายเดือนก่อน

    Make more videos Sir. Thank you for the content!!

  • @gabrielmenezes7237
    @gabrielmenezes7237 ปีที่แล้ว +1

    nice video

    • @DanVega
      @DanVega  ปีที่แล้ว

      Thanks

  • @normandrental2695
    @normandrental2695 9 หลายเดือนก่อน

    Love

  • @himanshubhatnagar4025
    @himanshubhatnagar4025 ปีที่แล้ว +2

    Thats really a great explanation,
    I have one more query: does constructor injection also use reflections internally?

    • @DanVega
      @DanVega  ปีที่แล้ว +1

      No. Field Injection uses reflection while constructor and setter injection do not.

  • @alisonanderson8957
    @alisonanderson8957 2 ปีที่แล้ว

    Hello!
    How does the private final field, and the loaded constructor affect Jpa? -- would a second empty controller be required?
    thanks for the excellent explanation!

  • @kyleryxn
    @kyleryxn 4 หลายเดือนก่อน

    IntelliJ Ultimate has the Spring initializer built in when you create a new project

  • @ambharathin
    @ambharathin ปีที่แล้ว

    Hello Dan, thanks for this highly insightful video!
    This leaves me with a rather rudimentary question.
    Since it is fully possible to code constructor injection (with arguments) without the Spring Framework (since this is how I've been doing dependency in my non-Spring code bases like AWS Lambdas), what are the other benefits that are provided by Spring, purely from the standpoint of constructor injection? In the grand scheme of things, agreed that Spring does a lot more under the hood but just wanted to understand the *real* relevance of Spring in case of contructor-injection-based dependency management. Thanks in advance for your time on this!

  • @maksadnahibhoolna-wc2ef
    @maksadnahibhoolna-wc2ef ปีที่แล้ว

    What's the difference between these two ways you are instantiating the object of VideoRepository at following timestamps :
    The way you have instantiated repository object at 15:20
    v/s
    The way you have instantiated repository object (using constructor DI) at 18:08
    @DanVega I was little confused since whether the code of former timestamp also a constructor based dependency Injection ?

  • @gennadyshevchenko7940
    @gennadyshevchenko7940 ปีที่แล้ว

    I thought that type of injection depends on architecture. If I want to change behavior of video-controller in runtime (without creating another video-controller with required behavior), it's necessary to use injection with setters. If I require immutable bean with all not-null dependencies, I need to use injection with constructor.

  • @age.vampire9767
    @age.vampire9767 ปีที่แล้ว

    When doing DI, what is the lifecycle of DI item, is it always be singlton in spring ?

  • @ayushpandey7
    @ayushpandey7 2 ปีที่แล้ว +1

    Never knew Mark Knopfler is high on spring as well

  • @BrunoSturniolo
    @BrunoSturniolo หลายเดือนก่อน

    why you have color in your output console? i have to add the line in the .properties; spring.output.ansi.enabled=Always
    How do you do to do it by default?

  • @wandacode
    @wandacode 27 วันที่ผ่านมา

    22:39 how videoRepository can be null with autowired if it is being managed by spring 🤔

  • @abhinavpandey3356
    @abhinavpandey3356 ปีที่แล้ว

    Hi Dan are u using vs code?if yes which dependencies to install to get auto suggestions.

  • @wandacode
    @wandacode 27 วันที่ผ่านมา

    22:38 how can be VideoRepository null if it’s being managed by Spring.

  • @vietanh722
    @vietanh722 ปีที่แล้ว

    nice plugin suggestion. What is that?

  • @cipherxen2
    @cipherxen2 ปีที่แล้ว

    Autowired is useful when there is circular dependency.

    • @meilyn22
      @meilyn22 3 หลายเดือนก่อน

      You must be doing something wrong in the first place to land in that area.

  • @glowiever
    @glowiever 2 ปีที่แล้ว

    can I make the repository an interface? how would spring resolve it? how to bind an implementation into an interface in the way of spring?

    • @DanVega
      @DanVega  2 ปีที่แล้ว

      You could make it an interface... I'm not quite sure what you're asking though? Do you have an example?

  • @USONOFAV
    @USONOFAV 2 ปีที่แล้ว +2

    I still don't get what Inversion of Control is. Inverting control from what? Like inverting the creation of object from a class to container?

    • @DanVega
      @DanVega  2 ปีที่แล้ว +3

      Exactly. Instead of you having to create an instance and supply a dependency you are asking the framework to handle that for you.

    • @USONOFAV
      @USONOFAV 2 ปีที่แล้ว

      @@DanVega ok i got it thanks for the response. So probably the reason why Martin Fowler want to call it Dependency Injection instead of IoC from his 2004 article about Spring and PicoContainer, because the term is kinda confusing.

    • @JamesStansell
      @JamesStansell ปีที่แล้ว

      If you know the terms declarative and imperative that might help to understand IOC in general. Even with the spring framework, at least in the old days before the annotations were added, the dependencies were declared in an xml file that the operations team could modify as needed without having to recompile the application. Only I doubt that it was done that way in practice very often. When coupled with external property configuration, using annotations to declare the dependencies the way Dan explained works well for most applications.

  • @teaadvice4996
    @teaadvice4996 ปีที่แล้ว

    What is Giving u all those suggestions in intellij

  • @Hamzul.
    @Hamzul. ปีที่แล้ว +1

    21:00 why @AutoWired is bad

    • @DanVega
      @DanVega  ปีที่แล้ว

      The autowired annotation isn't bad but field injection is. You can do a search on that but tldr; don't use it.