@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:

public class TestController{

    @Value("${database.connector.name}")
    private String name;
    private JdbcTemplate jtm;

    @Autowired
    public void setJdbcTemplate(ApplicationContext context){
        jmt = (JdbcTemplate)context.getBean(name);
    
    }
}

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

@Resource
@Qualifier("nk1")
private Car volkswagen;

@Autowired
@Qualifier("nk1")
private Car volkswagen;

@Inject
@Qualifier("nk1")
private Car volkswagen;

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

org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [javabeat.net.basics.Car] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true),
@org.springframework.beans.factory.annotation.Qualifier(value=nkl)}

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