java – Spring setter injection not mandatory

java – Spring setter injection not mandatory

DI exists in two major variants: Constructor-based dependency injection and Setter-based dependency injection.

Constructor-based Dependency Injection

Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency.

Setter-based Dependency Injection

Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or a no-argument static factory method to instantiate your bean.

Again, constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state (not having passed its collaborators). In other words, when using constructor injection you do not have to use a dedicated mechanism to ensure required properties are set (other than normal Java mechanisms).

But in setter based injection if the dependencies is not found the object is created, but the dependent object will be null. Means, setter injection does not ensures dependency Injection. You can find a detailed article here.

Note that use of the @Required annotation on a setter method can be used to make the property be a required dependency.

if you are using setter based injection in your bean then your bean will initialise no matter all dependencies have been resolved or not, but you will get NPE when try to use these non resolved/initialised dependencies in your code.
But in Constructor based injection your bean will initialise once all dependencies have been resolved.

java – Spring setter injection not mandatory

Whenever we use @Autowired, Spring makes sure the relevant bean exists and gets injected for use.
If this cannot be done, Spring throws an exception and the application fails to start.

The statement actually is in reference to testing your code. By this I mean, If using setter based dependency injection it may be possible that one will forget to inject the required bean and the corresponding test cases might fail.

constructor based dependency injection ensures that one has to init all required beans before actually using the required code.

You can read it in detail over here

Leave a Reply

Your email address will not be published. Required fields are marked *