#11 Autowire in Spring
Summary
TLDRIn this tutorial, the instructor delves into the concept of Autowiring in Spring Framework without the use of Spring Boot. They start by setting up a basic example with a 'Developer' class dependent on a 'Computer' interface, implemented by 'Laptop' and 'Desktop' classes. The video demonstrates how to configure Spring XML for dependency injection, troubleshoot common issues like null pointer exceptions, and utilize autowiring by name and by type. The instructor also explains the importance of unique bean IDs and the use of the 'primary' attribute to resolve autowiring conflicts. Finally, they show how to retrieve beans by type in the application context, providing a clear understanding of autowiring in Spring.
Takeaways
- 📚 The video continues a series on the Spring Framework, focusing on Auto-wiring without Spring Boot.
- 💡 Auto-wiring is a feature that was previously covered in the context of Spring Boot, and this video explores it in the standard Spring Framework.
- 🖥️ The presenter introduces the concept of a 'Computer' interface with 'Laptop' and 'Desktop' as its implementations, emphasizing the importance of interfaces in coding.
- 🔄 The 'Developer' class is modified to depend on a 'Computer' interface instead of a specific 'Laptop', demonstrating the principle of dependency inversion.
- 🛠️ The video shows the process of refactoring code to use interfaces and how to implement them in classes, which is crucial for flexibility and maintainability.
- 📝 Errors in bean creation due to constructor changes are discussed, highlighting the importance of matching constructors with XML configurations in Spring.
- 🔧 The presenter demonstrates how to set properties in the Spring XML file and the implications of referencing bean IDs for dependency injection.
- 🔗 The concept of 'byName' and 'byType' autowiring is explained, showing how Spring resolves dependencies based on property names or types.
- 🚫 The video points out the limitations of 'byName' autowiring when two beans have the same ID, which can lead to confusion and errors.
- 🏷️ The use of the 'primary' attribute in autowiring is introduced to resolve conflicts when multiple beans of the same type are present.
- 🔑 The video concludes with a discussion on retrieving beans by type using the 'App' Java configuration, offering an alternative to bean ID-based retrieval.
Q & A
What is the main topic of this video script?
-The main topic of this video script is about Autowiring in the Spring Framework without Spring Boot.
What is the purpose of creating a 'Computer' interface in the script?
-The purpose of creating a 'Computer' interface is to abstract the common functionalities of a laptop and a desktop, allowing the 'Developer' class to be dependent on a computer in general, rather than a specific type.
Why are the 'Laptop' and 'Desktop' classes implementing the 'Computer' interface?
-The 'Laptop' and 'Desktop' classes implement the 'Computer' interface to provide specific implementations of the computer concept, allowing them to be used interchangeably in the context of the 'Developer' class.
What changes are made to the 'Developer' class to make it dependent on a 'Computer' instead of a 'Laptop'?
-The 'Developer' class is changed to have a 'Computer' type for its 'comp' property instead of a 'Laptop'. The constructor that took a 'Laptop' as a parameter is removed, and getter and setter methods are generated for the 'comp' property of type 'Computer'.
What is the significance of the 'autowire' attribute in the Spring XML configuration?
-The 'autowire' attribute in the Spring XML configuration is used to enable autowiring of bean properties by name or by type, allowing Spring to automatically inject the appropriate bean into the property.
What is the issue when trying to autowire by name with two beans having the same name?
-When trying to autowire by name with two beans having the same name, Spring cannot determine which bean to inject, resulting in a confusion and a potential runtime error.
How can you resolve the issue of having two beans with the same name for autowiring by name?
-You can resolve this issue by either giving unique names to the beans, or by changing the autowiring strategy to 'byType', or by using the 'primary' attribute to specify a preferred bean when there are multiple candidates.
What does the 'primary' attribute do in the context of autowiring by type?
-The 'primary' attribute indicates that among multiple beans of the same type, the one marked as 'primary' should be given preference when autowiring by type.
How can you retrieve a bean by its type instead of its name in the Spring ApplicationContext?
-You can retrieve a bean by its type using the 'getBean(Class<T> requiredType)' method of the ApplicationContext, which returns an instance of the bean that matches the required type.
What is the problem with using autowiring without specifying a strategy when there are multiple beans of the same type?
-The problem with using autowiring without specifying a strategy when there are multiple beans of the same type is that Spring cannot decide which bean to inject, leading to an ambiguity and a potential 'NullPointerException'.
Outlines
😀 Introduction to Autowiring in Spring Framework
In this segment, the video script introduces the concept of autowiring in the Spring Framework, building upon previous discussions on constructor and setter injection. The speaker begins by referencing the Spring Boot context and then transitions to a more detailed exploration of autowiring outside of Spring Boot. The script discusses the creation of a 'Computer' interface and two implementations, 'Laptop' and 'Desktop', to demonstrate the autowiring process. The speaker also refactors the 'Developer' class to depend on the 'Computer' interface rather than a specific implementation, emphasizing the importance of loose coupling in software design. The segment concludes with an error encountered when removing a constructor, highlighting the need to update the Spring configuration file to reflect changes in the class dependencies.
😉 Exploring Autowiring with Different Bean Implementations
This paragraph delves into the intricacies of autowiring when multiple implementations of an interface exist. The script describes how to set up bean properties in the Spring XML configuration file, specifically focusing on the 'Developer' class's dependency on a 'Computer' object. It explains how the 'Laptop' bean can be injected into the 'Developer' class by referencing the bean ID. The speaker then discusses the implications of creating additional beans, such as 'Desktop', and how they can be injected into the 'Developer' class. The script also touches on the limitations of autowiring by name when multiple beans with the same ID are present, leading to a discussion of autowiring by type as an alternative approach. The segment concludes with a demonstration of how Spring handles autowiring by type when two beans of the same type are available, resulting in an error due to ambiguity.
🎓 Advanced Autowiring Techniques and Spring Boot Comparison
The final paragraph of the script discusses advanced autowiring techniques, including the use of the 'primary' attribute to resolve ambiguity when multiple beans of the same type are available for autowiring. The speaker illustrates how to specify a primary bean to be preferred by Spring when autowiring by type. Additionally, the script introduces the concept of retrieving beans by type using the 'getBean' method in the Spring ApplicationContext, which allows for a more type-safe and less verbose approach compared to searching by bean name. The speaker draws parallels between the XML-based configuration in the traditional Spring Framework and the annotation-based configuration in Spring Boot, emphasizing the underlying principles that remain consistent across both frameworks. The segment ends with an invitation for viewers to continue exploring Spring Boot and to look forward to more in-depth project discussions in future videos.
Mindmap
Keywords
💡Spring Framework
💡Constructor Injection
💡Setter Injection
💡Autowiring
💡Spring Boot
💡Interface
💡Implementation
💡Bean
💡XML Configuration
💡Primary Attribute
💡GetBean
Highlights
Introduction to Spring Framework's Autowiring without Spring Boot.
Explanation of Constructor and Setter Injection as prerequisites for Autowiring.
Creating a 'Computer' interface and 'Desktop' class as an implementation.
Refactoring 'Laptop' class to implement the 'Computer' interface.
Modifying 'Developer' class to depend on 'Computer' instead of 'Laptop'.
Removing the specific constructor in 'Developer' to allow for autowiring.
Error encountered due to removal of constructor and XML configuration mismatch.
Adjusting XML configuration to set properties for 'Developer' bean.
Injecting 'Laptop' as a 'Computer' object into 'Developer' using XML references.
Demonstration of successful autowiring with 'Laptop' object.
Adding 'Desktop' bean to the XML configuration for alternative autowiring.
Explanation of how autowiring selects beans based on names and types.
Using 'autowire' attribute in XML to enable automatic bean wiring.
Challenges with autowiring when multiple beans have the same name.
Using 'byType' autowiring to resolve ambiguity between 'Laptop' and 'Desktop'.
Utilizing 'primary' attribute to specify the preferred bean in case of type conflict.
Alternative approach of getting beans by type instead of by name in Spring.
Summary of autowiring concepts and their practical implementation in Spring Framework.
Transition to focusing more on Spring Boot in subsequent tutorials.
Transcripts
welcome back aliens my name is z readyy
and let's continue this series on Spring
framework now to this point we were able
to achieve Constructor and seter
injection it's time to talk about Auto
wiring if you remember when we talked
about spring boot we have done this in
Spring boot we have done with auto
wiring but here also without spring boot
let's try to explore it and even before
we do that if you remember the spring
boot videos we have talked about
different classes and interfaces because
in this case we only have laptop and Dev
developer uh what we don't have is
computer interface and desktop
implementation of it so let's create
those and let's get forward so what I
will do is I will just go back here and
say let me just copy and paste or maybe
use the same a laptop class but this
time we'll name it as
desktop and in desktop we'll change
certain things I will just close this
part and in desktop what I will do is
when I say uh the structor should be
desktop created and in the compiling I
will say compiling with or compiling in
desktop okay so these are the changes I
made so in the laptop it says compiling
I will just change it to compiling in
laptop okay uh nothing fancy just two
different classes for the same concept
and when I say concept these two are are
the same type right so they both are
computer so what I will do is I will
just extract the interface out of
it extract the interface and and we'll
name this as computer uh you can do this
in different IDs otherwise you can just
simply create an interface and have this
method which we want so if you go to
computer okay vo compile so I wanted
this method I don't know what I made
some mistake while refactoring it
doesn't matter so you can see we got the
interface which is computer and both
these classes the laptop and desktop
need to implement computer so I will say
implements computer if this is not
happening by default in your ID just try
to manually type it that should not be a
problem so we got the interface computer
and then we got two implementation
laptop and desktop okay just to go with
this concept of coding for the
interfaces now since we have made those
changes I also want to change my
developer now developer should not be
dependent on a laptop right so developer
should be dependent on a computer so I
will just make mention computer here and
here also I will just say this is a type
I would say comp even comp works okay
and then since we have made those
changes I have to also change the in
fact I will just remove this particular
Constructor of parameters construct of
Dev and then we have to make two changes
here so when I said two changes
basically I'm I want to change the G
sets not for laptop this time but for
the computer so I will just say generate
G sets for the computer I will say okay
and now we got this two G set I me we
got these two methods and then uh here
also in the build I will say com.
compile not laptop do compile because as
a developer it doesn't matter which one
you want to use which one you're using
basically desktop or laptop it should
work right uh so we made few changes and
will this work that's a question let's
try I have not made any changes in the
uh spring.xml file so there's no
confusion change let's see if this works
and let's see what breaks when we do
that so yeah we got the error and if you
see the error it says error creating a
bean DEA of course but why uh it says
cannot resolve to a Constructor yeah
because we have removed the Constructor
and I think in the XML file we are still
using this Constructor so what I will do
is I will just remove everything since
we know now how to we use it so let me
remove everything okay so Dev is
basically empty now and we got a laptop
and the name for the ID for the laptop
is Lab One what I want to do is I want
to set some properties right so we have
to basically set the property for uh the
two things if if you go to Dev I'll just
close this we got two properties we got
comp and we got age and maybe we don't
even need age now let's only focus on
comp okay U of course even if it is
there it should not make any difference
but I just want to keep the code a bit
clean so let's say we have only one
dependency which is of computer here and
if I go back to the XML file now the dev
needs to have a computer object the
property so I will say property the name
of the property is comp but what should
be the value of course you cannot set a
Valu is because this is not a primitive
type this is a reference type so inste
of value it should be ref the question
is what it is referring to now computer
is an interface right so if you look at
developer it is dependent on a computer
and computer itself is interface so I
can't simply create an object of the
interface right so I have to look for
the implementation and in this case we
got two implementation we got desktop
and we got laptop but if you look at the
bean creation we are not creating the
object for desktop we are just creating
the object for laptop so basically in
your container when you run this if it
is it works basically you will get two
objects one for your developer and one
for your laptop okay so we will get
these two objects now laptop itself is a
computer right so can we just inject
laptop in this developer when it is
asking for uh the comp yes we can so
what we can simply do is we already have
the object created for laptop which is
lab one we can simply refer it here our
job is done right so now if I run this I
hope this time it will work and if not
let's debug it but it works you can see
it says uh working on the awesome
project laptop Constructor developer
Constructor no where it's sayings
desktop construct because we have not
geted the bean here and then it says
compiling in laptop so perfectly makes
sense but how about I want the object
for the desktop as well so I can say
Bean ID and I can say this is desk one
and I say class the class is com.
telescope. uh desktop and then in here
okay we don't have any property there so
now we got two objects and now if I on
this look at the output basically you
will also get the desktop Constructor so
it depends upon how many beans you
mention here okay so now you even got
the desktop object here okay so in total
we got three objects but in developer
Which object we are using we are using
the lap one again we have done this
before we know how it is referring now
but yeah if you want to say this is desk
one that's your choice I mean you can
mention what property you want do you
want a desktop or do you want a laptop
so you can change that in XML file and
now it says compiling in desktop so the
way you change that it will basically
inject that particular object in the
developer so it will inject this not
this one okay things are working out but
what if I change the name here so let's
say uh the ID for laptop is comp okay
and will this work now of course I have
to change here as well it will work
because it will not be using com it will
be using desk one but what if I say comp
will there be an issue if you have the
same name uh of course not see this comp
is basically referring to the developer
variable name which is comp and the
second comp this one is referring to the
name of the Bean or the IDE of The Bean
which is laptop Bean which is comp and
now if you done this of course it will
refer to the laptop and you can see it
says compiling a laptop so our theory is
working but don't you think these two
names are same when you say name is comp
uh the reference also comp what if I
just skip this part I mean I spring is
so awesome right uh if spring is that
awesome I want spring to actually
connect that automatically what we are
doing is we are doing wiring and I want
this wiring to be happening
automatically we have done that in
spring board here also if I just comment
it and if I run uh let's see if spring
is happy about it no no spring is not
happy spring says it's still null null
point of exception it's because we are
commenting it and we are assuming that
it will do auto wiring but spring says
no no no I will not automatically do it
you have to tell me to do it so what you
can do is you can just in the tag you
can add one more attribute called
autowire if you can see autowire and you
can say by name now what it will do is
it will check okay so in this particular
developer class we got only one property
of comp the computer property the name
is comp what I will do is I will search
for this name in this particular
container so in this container do we
have any object with com yes so we have
this name here so for this object we
have com for this object it is desk one
so it was search hey do we have any
object with name Comm and yes we do have
it uh which is here so it will try to
connect it and that's Auto wiring so if
I run this your spring is Happy it says
compiling in laptop he happy so
basically that's how you use autowire
but the problem is you can't use desktop
here because you can't have two things
with the same name example if you if you
say both are comp uh there will be a
confusion and you can see a huge
confusion it says being com is already
used right so we cannot use the same ID
two times and that's why they IDs right
it should be unique uh so we can have it
comp and comp one but let's say uh if
you want to use desktop as well one
thing you can do you can remove the IDS
or uh you can change by saying hey I
don't want to go by name I want to go by
type even you can do that so this time
I'm not saying by name I'm saying by
type so when you're searching for comp
is basically searching for these two
components here and says okay we got
laptop and we got desktop both are
computer what I will do time bu is I
will just commend this laptop and let's
see if that works so by type it is
searching for the type of a computer and
desktop is a type of computer but the
problem starts when you have both now if
you see we got two beans of course they
have different name but doesn't matter
we are not even searching by name we
sear searching by type the type of
computer and desktop and laptop both are
computers and now if you this spring is
not happy spring says hey you know I was
searching for one but I found two there
are two beans which are claiming that
they are computers I can't I can't
select one I don't want to be biased as
a programmer we can be biased not the
framework so what we can say okay in
case of confusion give me the laptop so
I will say primary is equal to true so
you can use the primary attribute so
primary says in terms of confusion go
with this particular Bean which is the
laptop so we are saying primary is true
and we have done this in the spring boot
as well with the help of at primary
annotation but here I'm using the
attribute and it says uh compiling with
laptop uh so now I hope you are able to
connect what we have done in the spring
Boot and what is happening here of
course XML is not something we love
about but I just wanted to explain you
what is happening behind the scene so
now uh this laptop object is becomes the
primary one we can do actually one more
thing which which not talked about which
is the app. Java in this if you see we
are saying get bean and when you say get
bean we are asking for the ID right I
don't want to mention the ID what if I
mention the type of the object I want I
want the object of or not computer I
want the object of Dev now will this
work so we are not searching by name
here we're searching by type and when
you to search by type you don't even
have to type cust it so it reduces the
number of words you write and if you run
this it works right so you have a choice
you can you can get bean by name or you
can get bean by type so in this case uh
if you see the XML file the name is not
important the type is important so
you're searching for the object by type
so that that's how basically you work
with the autowire concept so that's it
from this video where we talked about
the auto wiring and I hope uh the spring
framework without spring boo makes sense
now uh enough of spring framework now
let let's focus on Spring boot more and
then we'll move towards the project so I
hope you enjoying the series where we
are talking about spring and spring boot
uh and it's time to focus more on spring
board bye-bye
5.0 / 5 (0 votes)