IDEA报错Could not autowire. No bea

2019-12-11  本文已影响0人  猫尾草

1. 问题描述

  在IDEA中使用Spring的注解@Autowired,程序能正常运行,但是idea标红报错Could not autowire. No beans of 'UserMapper' type found

2. 一个重要前提

  程序能正常运行,说明没有错误,bean真实存在。

3. 我遇到的两个场景(研究不深,其他场景不敢保证)

3.1 使用Mybatis,在@Service注解的类中用@Autowired导入Mapper类

  网上有另一个解决办法,在Application类添加@EnableAutoConfiguration注解,@Autowired确实不报错了,但是提示@EnableAutoConfiguration注解重复,因为@SpringBootApplication中包含@EnableAutoConfiguration

3.2 redis的config文件配置在公共模块common中

  有多个微服务A、B、C、D...等等,都要用到redis,使用相同的配置文件,但是连接不同的redis服务,因此把RedisTemplate的Bean放到common模块,供其他所有模块使用,在每个模块中定义自己的LettuceConnectionFactory。如下所示:

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;

@Configuration
public class RedisConfig {

    /**
     * 这里导入的bean:LettuceConnectionFactory,在其它模块中生成
     */
    @Resource
    private LettuceConnectionFactory redisConnectionFactory;

    @Bean
    public RedisSerializer fastJsonJsonRedisSerializer() {
        return new FastJsonRedisSerializer(Object.class);
    }

    @Bean
    @Primary
    public RedisTemplate initRedisTemplate(RedisSerializer fastJsonJsonRedisSerializer) {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(fastJsonJsonRedisSerializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(fastJsonJsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

  导入LettuceConnectionFactory时使用@Resource就不会报错。

3. 原因(根据各种查资料猜的)

  IDEA可以理解Spring的上下文,也就是能识别Spring的注解@Autowired,但是@Mapper@MapperScan注解是是Mybatis的,IDEA理解不了。
  IDEA拿到了Spring的注解@Autowired,就要去找@Autowired使用的bean;但是理解不了MyBatis的注解也是用来生成bean的,就找不到Mapper生成的Bean。
  common模块中确实不存在LettuceConnectionFactory的Bean,所以IDEA找不到。
  为什么换成@Resource就可以了呢?因为@Resource也不是Spring的注解,IDEA理解不了这是要找bean,就不会去找了。

4. 参考

  1. http://www.imooc.com/article/287865
  2. https://blog.csdn.net/myushu/article/details/79548442
上一篇 下一篇

猜你喜欢

热点阅读