【排错日记】spring之Consider defining a bean of type ‘com.xxx.XxxxService‘ in your configuration.

文章描述了一个在SpringBoot应用启动时由于bean定义错误导致的故障。具体表现为在@Controller中尝试通过@Autowired注入XxxxxService时找不到对应的bean。问题根源在于配置类中的@Bean方法名称重复,这导致Spring容器中只有一个bean实例。修正方法是确保每个@Bean方法的名称唯一,从而解决了冲突。
摘要由CSDN通过智能技术生成

文章目录

现象

如题,启动项目时,报错如下:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field messageTemplateService in com.xxx.XxxxxController required a bean of type 'com.xxx.XxxxxService' that could not be found.

The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.xxx.XxxxxService' in your configuration.

代码

  • 代码1
    //引用的地方
    @Autowired
    private MessageTemplateService messageTemplateService;
  • 代码2
@Configuration
@ConditionalOnClass(XxxxxService.class)
public class XxxxxServiceAutoConfiguration {
    
    @Bean
    @ConditionalOnMissingBean(XxxxxService.class)
    public XxxxxService uploadService(TokenConfigService tokenConfigService) {
        log.info("XxxxxService build start");
        XxxxxService xxxxxService = new XxxxxService();
        xxxxxService.setTokenConfigService(tokenConfigService);
        log.info("XxxxxService build end");
        return xxxxxService;
    }
}

  • 代码3
@Configuration
@ConditionalOnClass(UploadService.class)
public class UploadServiceAutoConfiguration {
    
    @Bean
    @ConditionalOnMissingBean(UploadService.class)
    public UploadService uploadService(TokenConfigService tokenConfigService) {
        log.info("UploadService build start");
        UploadService uploadService = new UploadService();
        uploadService.setTokenConfigService(tokenConfigService);
        log.info("UploadService build end");
        return uploadService;
    }
}

分析

  1. 本质是对象XxxxxService在spring容器不存在。
  2. 删除【代码2】,恢复正常
  3. 分析【代码2】与【代码3】互相影响,比对发现@Bean修饰的方法名称重复了,改成不一样的解决~
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值