关于Spring Boot自动注入出现Consider defining a bean of type ‘xxx‘ in your configuration问题解决方案

在Spting Boot项目中自然要使用实现自动注入来体现Spring IOC的便利了, 但是我在实施过程中出现了这么一个问题, 如下, 这里找到解决办法记录下来,供遇到同样的问题的同僚参考

2021-04-08 23:07:04.596 ERROR 18156 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Parameter 1 of constructor in com.xxx.xxx.xxx.xxx.xxx.xxx.Xxxxx required a bean of type 'com.xxx.xxx.xxx.xxx.xxx.xxx.Xxx' that could not be found.


Action:

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

然后我又看了下自己写的几个类以及注解, 如下,感觉写的都没有问题

控制器 StudentController 

@RestController
public class StudentController {

	@Autowired
	private StudentService studentService;

	@GetMapping("/{id}" )
    public String getById(@PathVariable("id" ) String id) {
        return studentService.getById(id);
    }
	
}

接口 HelloService

@Component
public class StudenService {

    public Student getById(String id) {
    	return "暂无用户信息";
    }
	
}

根据英文的提示是在配置中找不到一个指定自动注入类型的bean,经过多方排查得出结论:

正常情况下加上@Component注解的类会自动被Spring扫描到生成Bean注册到spring容器中, 既然他说没找到, 也就是该注解被没有被spring识别, 问题的核心关键就在application类的注解SpringBootApplication上

@SpringBootApplication
public class StudentApplication {
	
	public static void main(String[] args) {
		SpringApplication.run(StudentApplication.class, args);
	}

}

这个注解其实相当于下面这一堆注解的效果, 其中一个注解就是@Component, 在默认情况下只能扫描与控制器在同一个包下以及其子包下的@Component注解, 以及能将指定注解的类自动注册为Bean的@Service@Controller和@ Repository, 至此明白问题所在, 之前我将接口与对应实现类放在了与控制器所在包的同一级目录下, 这样的注解自然是无法被识别的

  1. @SpringBootConfiguration

  2. @EnableAutoConfiguration

  3. @ComponentScan(excludeFilters={@Filter(type=CUSTOM, classes={TypeExcludeFilter.class}), @Filter(type=CUSTOM, classes={AutoConfigurationExcludeFilter.class})})

  4. @Target(value={TYPE})

  5. @Retention(value=RUNTIME)

  6. @Documented

  7. @Inherited

至此, 得出两种解决办法:
  1 . 将接口与对应的实现类放在与application启动类的同一个目录或者他的子目录下, 这样注解可以被扫描到, 这是最省事的办法
  2 . 在指定的application类上加上这么一行注解, 手动指定application类要扫描哪些包下的注解, 见下图 

@SpringBootApplication
@ComponentScan(basePackages = {"com.study.service", "com.study.common"})
public class StudentApplication {
	
	public static void main(String[] args) {
		SpringApplication.run(StudentApplication.class, args);
	}

}

通过这两种方式, 那个找不到指定Bean的错误就成功解决了!!!
PS:控制器Controller也要放在与application同级或者子目录下, 道理大致一样

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值