#11 Autowire in Spring

Telusko
21 May 202412:10

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

00:00

πŸ˜€ 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.

05:01

πŸ˜‰ 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.

10:03

πŸŽ“ 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

Spring Framework is an open-source Java platform that provides a comprehensive infrastructure for developing Java applications. In the video, it is the main topic discussed, with a focus on its dependency injection features, which are crucial for managing the components within an application.

πŸ’‘Constructor Injection

Constructor Injection is a technique in Spring where dependencies are injected into a Spring bean through its constructor. This is a key concept in the script, where the speaker discusses transitioning from constructor injection to autowiring.

πŸ’‘Setter Injection

Setter Injection is another method of dependency injection in Spring, where dependencies are injected through setter methods. The script mentions this as a previous topic, indicating the progression from basic to more advanced injection techniques.

πŸ’‘Autowiring

Autowiring is a feature in Spring that allows the framework to automatically resolve and inject dependencies into a bean. The video script discusses how to implement autowiring without Spring Boot, demonstrating how Spring can automatically wire beans based on type or by name.

πŸ’‘Spring Boot

Spring Boot is a project that simplifies the bootstrapping and development of new Spring applications. The script contrasts the autowiring process in Spring Boot with that in the traditional Spring Framework, highlighting the ease of use in Spring Boot.

πŸ’‘Interface

In the context of the video, an interface is a Java construct that defines a contract for a group of methods without implementing the methods. The script uses the 'Computer' interface as an example to demonstrate the concept of abstraction and implementation in object-oriented programming.

πŸ’‘Implementation

Implementation refers to the concrete classes that provide the actual code for the methods declared in an interface. The script mentions 'Laptop' and 'Desktop' as implementations of the 'Computer' interface, illustrating the relationship between interfaces and their implementations.

πŸ’‘Bean

In Spring, a bean is an object that is managed by the Spring IoC container. The script discusses the creation of beans for 'Developer', 'Laptop', and 'Desktop', and how these beans are wired together using autowiring.

πŸ’‘XML Configuration

XML Configuration is a way to configure Spring beans using XML files. The script explains how to set up autowiring in the Spring XML configuration file, which is a traditional approach before the introduction of annotations and Java config.

πŸ’‘Primary Attribute

The 'primary' attribute in Spring is used to indicate the preferred bean when there are multiple candidates for autowiring by type. The script uses the 'primary' attribute to resolve the ambiguity when there are two beans of the same type.

πŸ’‘GetBean

GetBean is a method in Spring used to retrieve beans from the Spring application context. The script discusses using 'getBean' to retrieve a bean by type, which is a flexible way to access beans without specifying an ID.

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

play00:00

welcome back aliens my name is z readyy

play00:02

and let's continue this series on Spring

play00:03

framework now to this point we were able

play00:05

to achieve Constructor and seter

play00:08

injection it's time to talk about Auto

play00:11

wiring if you remember when we talked

play00:13

about spring boot we have done this in

play00:15

Spring boot we have done with auto

play00:17

wiring but here also without spring boot

play00:20

let's try to explore it and even before

play00:22

we do that if you remember the spring

play00:24

boot videos we have talked about

play00:26

different classes and interfaces because

play00:29

in this case we only have laptop and Dev

play00:32

developer uh what we don't have is

play00:34

computer interface and desktop

play00:35

implementation of it so let's create

play00:38

those and let's get forward so what I

play00:40

will do is I will just go back here and

play00:42

say let me just copy and paste or maybe

play00:45

use the same a laptop class but this

play00:47

time we'll name it as

play00:50

desktop and in desktop we'll change

play00:53

certain things I will just close this

play00:54

part and in desktop what I will do is

play00:56

when I say uh the structor should be

play01:00

desktop created and in the compiling I

play01:03

will say compiling with or compiling in

play01:07

desktop okay so these are the changes I

play01:09

made so in the laptop it says compiling

play01:11

I will just change it to compiling in

play01:13

laptop okay uh nothing fancy just two

play01:16

different classes for the same concept

play01:19

and when I say concept these two are are

play01:20

the same type right so they both are

play01:22

computer so what I will do is I will

play01:23

just extract the interface out of

play01:27

it extract the interface and and we'll

play01:30

name this as computer uh you can do this

play01:33

in different IDs otherwise you can just

play01:34

simply create an interface and have this

play01:36

method which we want so if you go to

play01:38

computer okay vo compile so I wanted

play01:41

this method I don't know what I made

play01:43

some mistake while refactoring it

play01:45

doesn't matter so you can see we got the

play01:47

interface which is computer and both

play01:49

these classes the laptop and desktop

play01:52

need to implement computer so I will say

play01:55

implements computer if this is not

play01:57

happening by default in your ID just try

play01:59

to manually type it that should not be a

play02:01

problem so we got the interface computer

play02:04

and then we got two implementation

play02:05

laptop and desktop okay just to go with

play02:08

this concept of coding for the

play02:09

interfaces now since we have made those

play02:11

changes I also want to change my

play02:13

developer now developer should not be

play02:14

dependent on a laptop right so developer

play02:17

should be dependent on a computer so I

play02:19

will just make mention computer here and

play02:22

here also I will just say this is a type

play02:25

I would say comp even comp works okay

play02:28

and then since we have made those

play02:30

changes I have to also change the in

play02:32

fact I will just remove this particular

play02:34

Constructor of parameters construct of

play02:36

Dev and then we have to make two changes

play02:39

here so when I said two changes

play02:41

basically I'm I want to change the G

play02:44

sets not for laptop this time but for

play02:45

the computer so I will just say generate

play02:48

G sets for the computer I will say okay

play02:51

and now we got this two G set I me we

play02:54

got these two methods and then uh here

play02:57

also in the build I will say com.

play02:58

compile not laptop do compile because as

play03:01

a developer it doesn't matter which one

play03:02

you want to use which one you're using

play03:04

basically desktop or laptop it should

play03:06

work right uh so we made few changes and

play03:10

will this work that's a question let's

play03:12

try I have not made any changes in the

play03:14

uh spring.xml file so there's no

play03:16

confusion change let's see if this works

play03:18

and let's see what breaks when we do

play03:19

that so yeah we got the error and if you

play03:22

see the error it says error creating a

play03:25

bean DEA of course but why uh it says

play03:28

cannot resolve to a Constructor yeah

play03:30

because we have removed the Constructor

play03:33

and I think in the XML file we are still

play03:35

using this Constructor so what I will do

play03:36

is I will just remove everything since

play03:39

we know now how to we use it so let me

play03:41

remove everything okay so Dev is

play03:43

basically empty now and we got a laptop

play03:45

and the name for the ID for the laptop

play03:47

is Lab One what I want to do is I want

play03:48

to set some properties right so we have

play03:50

to basically set the property for uh the

play03:53

two things if if you go to Dev I'll just

play03:55

close this we got two properties we got

play03:57

comp and we got age and maybe we don't

play04:00

even need age now let's only focus on

play04:02

comp okay U of course even if it is

play04:05

there it should not make any difference

play04:07

but I just want to keep the code a bit

play04:09

clean so let's say we have only one

play04:11

dependency which is of computer here and

play04:13

if I go back to the XML file now the dev

play04:16

needs to have a computer object the

play04:19

property so I will say property the name

play04:21

of the property is comp but what should

play04:24

be the value of course you cannot set a

play04:26

Valu is because this is not a primitive

play04:27

type this is a reference type so inste

play04:30

of value it should be ref the question

play04:32

is what it is referring to now computer

play04:35

is an interface right so if you look at

play04:37

developer it is dependent on a computer

play04:39

and computer itself is interface so I

play04:41

can't simply create an object of the

play04:43

interface right so I have to look for

play04:44

the implementation and in this case we

play04:46

got two implementation we got desktop

play04:48

and we got laptop but if you look at the

play04:50

bean creation we are not creating the

play04:53

object for desktop we are just creating

play04:54

the object for laptop so basically in

play04:57

your container when you run this if it

play04:59

is it works basically you will get two

play05:01

objects one for your developer and one

play05:06

for your laptop okay so we will get

play05:08

these two objects now laptop itself is a

play05:10

computer right so can we just inject

play05:13

laptop in this developer when it is

play05:15

asking for uh the comp yes we can so

play05:18

what we can simply do is we already have

play05:20

the object created for laptop which is

play05:22

lab one we can simply refer it here our

play05:25

job is done right so now if I run this I

play05:28

hope this time it will work and if not

play05:30

let's debug it but it works you can see

play05:32

it says uh working on the awesome

play05:34

project laptop Constructor developer

play05:35

Constructor no where it's sayings

play05:37

desktop construct because we have not

play05:39

geted the bean here and then it says

play05:41

compiling in laptop so perfectly makes

play05:43

sense but how about I want the object

play05:45

for the desktop as well so I can say

play05:46

Bean ID and I can say this is desk one

play05:50

and I say class the class is com.

play05:53

telescope. uh desktop and then in here

play05:56

okay we don't have any property there so

play05:58

now we got two objects and now if I on

play06:00

this look at the output basically you

play06:01

will also get the desktop Constructor so

play06:03

it depends upon how many beans you

play06:05

mention here okay so now you even got

play06:08

the desktop object here okay so in total

play06:11

we got three objects but in developer

play06:13

Which object we are using we are using

play06:14

the lap one again we have done this

play06:16

before we know how it is referring now

play06:18

but yeah if you want to say this is desk

play06:20

one that's your choice I mean you can

play06:22

mention what property you want do you

play06:24

want a desktop or do you want a laptop

play06:26

so you can change that in XML file and

play06:27

now it says compiling in desktop so the

play06:30

way you change that it will basically

play06:32

inject that particular object in the

play06:34

developer so it will inject this not

play06:36

this one okay things are working out but

play06:39

what if I change the name here so let's

play06:42

say uh the ID for laptop is comp okay

play06:46

and will this work now of course I have

play06:48

to change here as well it will work

play06:50

because it will not be using com it will

play06:51

be using desk one but what if I say comp

play06:54

will there be an issue if you have the

play06:56

same name uh of course not see this comp

play06:58

is basically referring to the developer

play07:02

variable name which is comp and the

play07:04

second comp this one is referring to the

play07:06

name of the Bean or the IDE of The Bean

play07:07

which is laptop Bean which is comp and

play07:10

now if you done this of course it will

play07:11

refer to the laptop and you can see it

play07:13

says compiling a laptop so our theory is

play07:15

working but don't you think these two

play07:17

names are same when you say name is comp

play07:20

uh the reference also comp what if I

play07:22

just skip this part I mean I spring is

play07:25

so awesome right uh if spring is that

play07:28

awesome I want spring to actually

play07:30

connect that automatically what we are

play07:32

doing is we are doing wiring and I want

play07:35

this wiring to be happening

play07:36

automatically we have done that in

play07:37

spring board here also if I just comment

play07:40

it and if I run uh let's see if spring

play07:43

is happy about it no no spring is not

play07:45

happy spring says it's still null null

play07:47

point of exception it's because we are

play07:50

commenting it and we are assuming that

play07:51

it will do auto wiring but spring says

play07:53

no no no I will not automatically do it

play07:55

you have to tell me to do it so what you

play07:57

can do is you can just in the tag you

play08:00

can add one more attribute called

play08:01

autowire if you can see autowire and you

play08:04

can say by name now what it will do is

play08:07

it will check okay so in this particular

play08:09

developer class we got only one property

play08:11

of comp the computer property the name

play08:14

is comp what I will do is I will search

play08:16

for this name in this particular

play08:19

container so in this container do we

play08:20

have any object with com yes so we have

play08:23

this name here so for this object we

play08:25

have com for this object it is desk one

play08:29

so it was search hey do we have any

play08:30

object with name Comm and yes we do have

play08:32

it uh which is here so it will try to

play08:35

connect it and that's Auto wiring so if

play08:37

I run this your spring is Happy it says

play08:40

compiling in laptop he happy so

play08:43

basically that's how you use autowire

play08:46

but the problem is you can't use desktop

play08:48

here because you can't have two things

play08:50

with the same name example if you if you

play08:52

say both are comp uh there will be a

play08:54

confusion and you can see a huge

play08:57

confusion it says being com is already

play08:59

used right so we cannot use the same ID

play09:02

two times and that's why they IDs right

play09:04

it should be unique uh so we can have it

play09:07

comp and comp one but let's say uh if

play09:10

you want to use desktop as well one

play09:12

thing you can do you can remove the IDS

play09:14

or uh you can change by saying hey I

play09:16

don't want to go by name I want to go by

play09:19

type even you can do that so this time

play09:22

I'm not saying by name I'm saying by

play09:24

type so when you're searching for comp

play09:26

is basically searching for these two

play09:27

components here and says okay we got

play09:30

laptop and we got desktop both are

play09:32

computer what I will do time bu is I

play09:34

will just commend this laptop and let's

play09:36

see if that works so by type it is

play09:38

searching for the type of a computer and

play09:40

desktop is a type of computer but the

play09:43

problem starts when you have both now if

play09:45

you see we got two beans of course they

play09:48

have different name but doesn't matter

play09:50

we are not even searching by name we

play09:51

sear searching by type the type of

play09:54

computer and desktop and laptop both are

play09:57

computers and now if you this spring is

play10:00

not happy spring says hey you know I was

play10:03

searching for one but I found two there

play10:05

are two beans which are claiming that

play10:07

they are computers I can't I can't

play10:10

select one I don't want to be biased as

play10:13

a programmer we can be biased not the

play10:15

framework so what we can say okay in

play10:17

case of confusion give me the laptop so

play10:20

I will say primary is equal to true so

play10:23

you can use the primary attribute so

play10:25

primary says in terms of confusion go

play10:27

with this particular Bean which is the

play10:29

laptop so we are saying primary is true

play10:32

and we have done this in the spring boot

play10:34

as well with the help of at primary

play10:36

annotation but here I'm using the

play10:38

attribute and it says uh compiling with

play10:40

laptop uh so now I hope you are able to

play10:42

connect what we have done in the spring

play10:45

Boot and what is happening here of

play10:47

course XML is not something we love

play10:49

about but I just wanted to explain you

play10:51

what is happening behind the scene so

play10:53

now uh this laptop object is becomes the

play10:56

primary one we can do actually one more

play10:58

thing which which not talked about which

play11:00

is the app. Java in this if you see we

play11:03

are saying get bean and when you say get

play11:05

bean we are asking for the ID right I

play11:08

don't want to mention the ID what if I

play11:10

mention the type of the object I want I

play11:14

want the object of or not computer I

play11:15

want the object of Dev now will this

play11:18

work so we are not searching by name

play11:20

here we're searching by type and when

play11:23

you to search by type you don't even

play11:24

have to type cust it so it reduces the

play11:27

number of words you write and if you run

play11:29

this it works right so you have a choice

play11:33

you can you can get bean by name or you

play11:35

can get bean by type so in this case uh

play11:38

if you see the XML file the name is not

play11:40

important the type is important so

play11:42

you're searching for the object by type

play11:44

so that that's how basically you work

play11:46

with the autowire concept so that's it

play11:49

from this video where we talked about

play11:50

the auto wiring and I hope uh the spring

play11:53

framework without spring boo makes sense

play11:56

now uh enough of spring framework now

play11:59

let let's focus on Spring boot more and

play12:01

then we'll move towards the project so I

play12:03

hope you enjoying the series where we

play12:04

are talking about spring and spring boot

play12:07

uh and it's time to focus more on spring

play12:09

board bye-bye

Rate This
β˜…
β˜…
β˜…
β˜…
β˜…

5.0 / 5 (0 votes)

Related Tags
Spring FrameworkAutowiringConstructor InjectionSetter InjectionXML ConfigurationDependency InjectionJava DevelopmentInterface ImplementationBean ManagementSpring Boot