Return to site

๐Ÿƒ๐ŸŽ“ SPRING CERTIFICATION QUESTION: What is dependency injection and what are the advantages?

ยท spring,vcp

๐ƒ๐ž๐ฉ๐ž๐ง๐๐ž๐ง๐œ๐ฒ ๐ข๐ง๐ฃ๐ž๐œ๐ญ๐ข๐จ๐ง ๐Ÿ’‰ is a design pattern that implements ๐ˆ๐ง๐ฏ๐ž๐ซ๐ฌ๐ข๐จ๐ง ๐จ๐Ÿ ๐‚๐จ๐ง๐ญ๐ซ๐จ๐ฅ (๐ˆ๐จ๐‚) design principle, whereby objects only define their dependencies letting some other code to ๐ข๐ง๐ฃ๐ž๐œ๐ญ those dependencies during object creation. That is why this process is called an inversion: an object doesn't control โŒ๐Ÿ‘ฎ instantiation of its dependencies.

 

There are several dependency ๐ข๐ง๐ฃ๐ž๐œ๐ญ๐ข๐จ๐ง ๐ญ๐ฒ๐ฉ๐ž๐ฌ:

1. Constructor ๐Ÿ‘ทโ€โ™‚๏ธ injection - dependencies are provided through a constructor.

2. Setter โœ๏ธ injection - dependencies are provided through an exposed setter method.

3. Field โน๏ธ injection - dependencies are injected directly in the field, with no constructor or setter method.

In Java language field injection is performed with the help of 'magical' reflection ๐Ÿชž technology, so even private fields can be populated in that way.

Fields have to be annotated with the ๐ด๐‘ข๐‘ก๐‘œ๐‘ค๐‘–๐‘Ÿ๐‘’๐‘‘ annotation to become field injection candidates.

4. Interface ๐Ÿค injection - dependencies are provided through an exposed setter method of the implemented interface.

5. Method ๐Ÿ“ฆ injection - dependencies are provided from overridden methods of container-managed bean.

 

Dependency injection ๐š๐๐ฏ๐š๐ง๐ญ๐š๐ ๐ž๐ฌ are the following:

1. Code is cleaner ๐Ÿงผ (object configuration details are externalized)

2. Decoupling decreases ๐Ÿ“‰ between an object and its dependencies

3. Code is easier to test ๐Ÿงช using stubs or mocks

4. Facilitating single 1๏ธโƒฃ responsibility principle

 

Dependency injection ๐๐ข๐ฌ๐š๐๐ฏ๐š๐ง๐ญ๐š๐ ๐ž๐ฌ are the following:

1. Increased ๐Ÿ“ˆ number of classes

2. Creation of unnecessary ๐Ÿคทโ€โ™‚๏ธ interfaces

#spring #certificationquestion #vcp

 

 

All Posts
ร—

Almost doneโ€ฆ

We just sent you an email.ย Please click the link in the email to confirm your subscription!

OK