Sunday, December 18, 2022

Object Injections to Springs

 There are two ways to inject an object to Springs.

1) Field Injection


2) constructor Injection






Prefer to use constructor injection over field injection as it has some advantages.

Below are some disadvantages of using field injection.

- First, you do not need to use autowired annotation, with constructer injection so you can inject an object while you are writing a simple Java codes without adding any annotation

- One of two major advantages of constructor injection is that it allows to be in to be immutable,  (Observe that the variable is declared with "final" unlike in field injection)

since you can define the property as final and immutable objects helps to create more robust and thread-safe applications.

- Constructor injection also forces that the object is created with the required dependency as the constructor forces it.

- And finally, Spring doesn't use a reflection with constructor approach, unlike field injection as  reflection makes the application code to run slower since it involves types that are dynamic result at runtime.




No comments:

Post a Comment