Spring boot注入组件Bean named 'XXX' is expected to be of type 'TTT' but was actually of type 'TTT'

该错误的原因就是代码里面注入的组件名称重复了。

仔细检查 @Bean    @Resource 修饰的变量名称是不是有重复的。

@Bean是一个方法级别上的注解,Bean的ID为方法名字。

@Resource默认按照ByName自动注入,@Resource有两个重要的属性:name和type,而Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。

    @Resource(name="userDao")
    private UserDao userDao; // 用于字段上

@Autowired注解是按照类型(byType)装配依赖对象,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它的required属性为false,如下所示:

@Autowired(required = false)//
private DefaultDataProducer producer;

不过这种  @Autowired(required = false) 允许为null的注解没有任何意义,最好不要使用,@Autowired的目的就是要让对象有值,需要使用它,允许为null,不如不要注入该组件。

如果@Autowired想使用按照名称(byName)来装配,可以结合@Qualifier注解一起使用

    @Autowired
    @Qualifier("dataProducer")
    private DefaultDataProducer  dataProducer; 
 ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '@@成员变量类型@@': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named '@@成员变量名称@@' is expected to be of type 'io.github.rhwayfun.springboot.rocketmq.starter.common.DefaultRocketMqProducer' but was actually of type 'com.google.code.kaptcha.impl.DefaultKaptcha'

猜你喜欢

转载自blog.csdn.net/langeldep/article/details/83110431
ttt