@Autowired

https://www.baeldung.com/spring-autowire

1. Overview

This annotation allows Spring to resolve and inject collaborating beans into your bean.

2.Autowire Disambiguation

2.1 Autowiring by @Qualifier

The @Qualifier annotation can be used to hint at and narrow down the required bean:

eg:

public class FooService{
    @Autowired
    @Qualifier("fooFormatter")
    private Formatter formatter;
}

2.2 read the property file for the qualifier name

eg:

3.Conclusion

Although both @Qualifier and bean name fallback match can be used to narrow down to a specific bean, autowiring is really all about injection by type and this is how best to use this container feature.

4. Difference between @Resource, @Autowired and @Inject

In the above code, @Resource works fine. But, @Autowired and @Injects throws the following exception.

The main difference is that, @Autowired and @Inject works similar for 100% without any differentiation.These two annotations using AutowiredAnnotationBeanPostProcessor to inject dependencies. But,@Resource uses CommonAnnotationBeanPostProcessor to inject dependencies and there is difference in the order of checking.

@Autowired and @Inject

1.Matches by Type

2.Restricts by Qualifires

3. Matches by Name

@Resource

  1. Matches by Name

  2. Matches by Type

  3. Restricts by Qualifiers(ignored if match is found by name)

Last updated

Was this helpful?