Constructor Injection Vs Setter Injection.
1. Allows dependencies to be declared as final, and the constructor is the only way to initialize the final variables. When an object is intended to be used across multiple threads it is always required that the shared variables be either declared as final or volatile. Setter injection cannot fix this issue of final variables. By default Spring DI creates a singleton instance unless specified to create an instance for each call, via the attribute prototype. If it is required for different threads to use different instances, then Constructor injection is not mandatory. The requirement of declaring the variables as final is relaxed and so setter injection can provide different threads with different instances of the class.
2. Recursive dependencies, such as A depends on B and B depends on A can be solved by using a proxy. Constructor injection cannot be used with this. Guice creates a dynamic proxy that solves the issue.
3. In-constructor problem: Initialization requires a dependency in a circular dependency, which is not yet ready for use. (constructor calls the member function of the dependency.). There is no solution for this kind of mess when Constructor injection is used. Use Setter injection.
4. Constructor Pyramid Problem: If a class has a significant number of decencies and if it uses several different constructors to initialize into several different forms, it is said to have constructor pyramid problem. It is difficult to understand what constructor does what in such a scenario. Number of constructors needed grows exponentially in proportional to number of dependencies. Setter injection is ideal in such a scenario.
5. Setter injection is unusable in default singleton situation where an object instance is shared across multiple threads, as the decencies cannot be declared final.
6. Setter injection is error prone as it is not guaranteed to have all setters set in the object before being used, and it is not easy to detect that an object is not properly initialized until the method requiring that uninitialized decency is called during runtime.
7. In automatically generated code for the constructors, parameter names would be name1, name2 etc rather than the actual field names. This is hard to catch bugs where two different parameters are initialized or called in different order. If setter methods are used, this problem is easier to catch as fields names are obvious in setter methods.
No comments:
Post a Comment