@Autowired annotation



Using this annotation spring inject the required bean automatically.
@Autowired can be apply at constructor, field and method level.

There is nothing special about method naming convention, method name can be any type.

If spring will not find the specific matching bean then it will throw exception.
To avoid exception you can specify @Autowired(required=false).
If no bean found then it will leave the bean unwired. That entity will be null.
It can throw NPE. you need to put null check in such case.

@Component

Class Forest{
private Bird bird;
private Animal animal;

@Autowired

private Raptile raptile;

@Autowired

public BirdsImpl(Bird bird) {
this.bird = bird;
}

@Autowired(required=false)

public vodi haveAnimal(Animal animal){
this.animal = animal;
}
}

also you can use @Inject annotation which is provided by Java dependencies.

@Autowired is provided by spring.

When to use Which?

For mandatory cases whe you aiming for immutability, use Constructor injection.
For changing and optional dependencies use method level injection.
Try to Avoid field injection.