Sunday, July 25, 2021

@Autowired Spring boot

Spring framework provides a feature to inject the object dependency implicitly. There are several ways available to inject dependency.

We can use @Autowired in following manner

1. @Autowired annotation with constructor

This will helpful when you want to initialize the dependency (want to make sure with dependency) before the creation of object. This will avoid 'NullPointerExcption'. This will also helpful when we are writing JUnit tests.

public class classA{

@Autowired

public classA(classB b){

}

}

Note: If there is only one constructor then don't need to explicitly mark constructor with @Autowired (Spring 4.3 onwards).

But if there is multiple constructor in a class then you need to explicitly specify the that which constructor will be used for autowiring.


2. @Autowired with setter method

This will helpful if you want to execute some thing during dependency injection.

@Autowired

public void setB(B b){

}

3. @Autowired with property

When you have no setter method

@Autowired

private B b;


How Autowired works ?

byType: It first try to look for same type object, in this case property name and bean name can be different.

byName: If multiple beans of same type available then it will try with byName, in this property name and bean name should be same.

If there is any further ambiguity with name then @Qualifier("name of bean") annotation can be used to specifically autowire any bean. 




Labels: , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home