大家好,我是trikey。

最近在编写练手项目代码时,出现了Consider defining a bean of type 'xxx' in your configuration 问题,这里简单记录一下解决的方案。

一、问题场景

模块A:存放公共类和方法的模块,对应包名为:com.trikeymon。

模块B:业务模块,对应包名为:com.trikey.jwt ,在pom.xml中已经导入模块A。

问题:

当我在模块B的某个接口中使用@Autowired注入了模块A中定义的bean,启动项目时,出现 Consider defining a bean of type 'xxx' in your configuration 问题。

二、问题原因

每一个Spring项目都有独立的Spring容器去存储自己项目中所注册的bean,模块B中的Spring容器加载时未能将模块A中所定义的bean注册进Spring容器中,导致开发时@Autowired注入模块A中的bean进行使用时,找不到对应的bean,才会出现 Consider defining a bean of type 'xxx' in your configuration 问题。

三、解决办法

让模块B的Spring容器启动时,去扫描模块A包下的所有的组件并注册到模块B的Spring容器中,这样问题就解决了。

如下图所示:

package com.trikey.jwt;

import com.trikeymon.util.SpringContextUtil;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication(scanBasePackages = {"com.trikeymon","com.trikey.jwt"})
@MapperScan("${mybatis-plus.mapperPackage}")
public class TrikeySsoJwtApplication {

    public static void main(String[] args) {

        ConfigurableApplicationContext applicationContext = SpringApplication.run(TrikeySsoJwtApplication.class, args);
        SpringContextUtil.setApplicationContext(applicationContext);
    }

}

更多推荐

SpringBoot 出现 Consider defining a bean of type ‘xxx‘ in your configuration 问题解决方