Dependencies in Spring

1. What is Dependency Injection (DI) in Spring?

Inversion of Control (IoC) in Spring is implemented through Dependency Injection.
DI says that you just need to describe how the objects should be created rather than
creating your objects yourself. When you use DI, you don’t have to directly connect
your components and services in the code but you just need to describe which services
are required by which components. The IoC container is then responsible for
connecting all your components.
Therefore, DI is the primary reason for highly decoupled components that you find in
Spring applications.

2. What are the different types of dependency injection?

  • Constructor-based dependency injection: It injects the dependency via aconstructor. This means that the required components are passed into a class at the time of instantiation.
  • Setter-based dependency injection: It injects the dependency via a setter method. This involves calling setter methods on your beans after invoking a no-argument constructor.
  • Property based

3. Which type of DI would you suggest –Constructor-based or Setter-based?

It depends. You can use constructor-based DI for mandatory dependencies and setter-
based DI for optional dependencies. In setter-based DI, partial injection of
dependencies is possible. If you do not inject some, it will take the default values for
those primitives. On the other hand, in constructor-based injection, partial injection of
dependencies is not possible. This is because for calling a constructor we must pass all
the arguments, else an exception will be thrown.
So based on your requirements, use the proper type of DI.


4. Explain how Spring resolves dependencies.

Spring resolves dependencies as follows:

  • Spring creates the ApplicationContext and initializes it based on the configuration metadata where the beans are defined.
  • The dependencies for each bean is provided at the time of bean creation and is expressed in the form of properties, constructor arguments, or arguments to normal methods.
  • Each property or constructor argument is a set of value that is injected and is converted from its specified format to the actual type of that property or constructor argument.

5. How do you declare inter-bean dependencies?

Declaration of inter-bean dependencies is as simple as having one bean method call
another. However, this method works only when the @Bean method is declared
within a @Configuration class.
Another way of declaring inter-bean dependency is by taking the dependency as
a @Bean method parameter. The injection is now by type. The dependency would be
first resolved by type and if duplicates are found, by name.

Comments

Popular posts from this blog

Spring Annotations

Spring Data Access

Spring Model View Controller (MVC)