Search code examples
javaspringinversion-of-controlautowiredjava-ee-6

What's the difference between Autowire and Resouce annotations in Spring? Why I cannot substitute Resouce with Autowire?


I am trying to use Redis in Spring project. And I copied some code like this and it works well:

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource(name = "redisTemplate")
    private HashOperations<String, String, SomeObject> hashOps;

Notice that I defined 2 variables pointing to a same bean RedisTemplate, which is constructed in another file:

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate redisTemplate(
          RedisConnectionFactory connectionFactory,
          @Qualifier("customObjectMapper")  ObjectMapper objectMapper) {
// do the config things...
    }
}

===

Then an idea came up to me, I am wondering why the var of redisTemplate wearing @Autowire while the var of hashOps wearing @Resource, and why hashOps can work well as there is not a bean injected explicitly.

I replaced Autowire to the var hashOps as below:

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired(name = "redisTemplate") // instead of Resouce here
    private HashOperations<String, String, SomeObject> hashOps;

Expected enough, my App started failed. The spring container tells that there is no bean of HashOperations to look up.

Emm, so back to the caption: What's the difference between Autowire and Resouce annotations in Spring? Why I cannot substitute Resouce with Autowire?


Solution

  • Yes guys, I figured it out by a Chinese post here: https://xxgblog.com/2020/03/12/spring-redistemplate-listoperations/.

    Don't worry if you can't read Chinese. I looked up the newest official document of why we can use Resouce instead of Autowire: https://docs.spring.io/spring-data/data-redis/docs/3.2.x/reference/html/#redis:template

    The KEY is spring framework helps us to do the conversion things. Spring provides more than you imaged types linked to specific Redis operation type, such as ListOperations ,HashOperations ,ValueOperations ,SetOperations and many other so-called operations views, which you can find in the doc above.