当前位置: 首页 > news >正文

【源码解析】Spring Bean定义常见错误

案例1 隐式扫描不到Bean的定义

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

@RestController
public class HelloWorldController {@RequestMapping(path = "/hiii",method = RequestMethod.GET)public String hi() {return "hi hellowrd";}}
@SpringBootApplication
@RestController
public class ApplicationContext {public static void main(String[] args) {SpringApplication.run(ApplicationContext.class,args);}
}

发现不在同一级的包路径,这个URL访问失败,那么是什么原因呢
其实就在这个main所对应的类的注解上,SpringBootApplication有一个对应的注解那就是ComponentScan

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {@Filter(type = FilterType.CUSTOM,classes = {TypeExcludeFilter.class}
), @Filter(type = FilterType.CUSTOM,classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {

ComponentScan有一个属性是扫描对应的路径注解,

	/*** Base packages to scan for annotated components.*/@AliasFor("value")String[] basePackages() default {};

ComponentScanAnnotationParser.parse的方法,declaringClass所在的包其实就是主方法的包,也就是com.qxlx
在这里插入图片描述
好了,我们找到问题所在了,加一行这个自定义路径就可以了。

@ComponentScan("com.qxlx")

定义的Bean缺少隐式依赖

@Service
public class UserService {private String serviceName;public UserService(String serviceName) {this.serviceName = serviceName;}
}

一启动的时候,就发现异常了。

Parameter 0 of constructor in com.qxlx.service.UserService required a bean of type 'java.lang.Integer' that could not be found.
 @Beanpublic String serviceName() {return "qxlx";}

添加如下bean就可以修复。启动正常。

http://www.lryc.cn/news/219083.html

相关文章:

  • 由于找不到vcruntime140.dll无法继续执行代码
  • Perl安装教程
  • Docker数据卷使用过程中想到的几个问题
  • Angular 中的路由
  • 【市场分析】Temu数据采集销售额商品量占比分析数据分析接口Api
  • Python笔记——linux/ubuntu下安装mamba,安装bob.learn库
  • Redis之Java操作Redis的使用
  • 《网络协议》01. 基本概念
  • 设置Ubuntu网络代理
  • LeetCode----23. 合并 K 个升序链表
  • [极客大挑战 2019]LoveSQL 1
  • dji mini4pro 图片拷贝到电脑速度
  • 基于深度学习的目标检测算法 计算机竞赛
  • 前端面试题之CSS篇
  • 【SQL相关实操记录】
  • Python爬虫实战-批量爬取下载网易云音乐
  • LeetCode 面试题 16.14. 最佳直线
  • Spring Boot创建多模块项目
  • Node.js、Chrome V8 引擎、非阻塞式I/O介绍
  • 企业服务总线ESB有什么作用?和微服务有什么区别?会如何发展?
  • NLP之LSTM原理剖析
  • ESP32网络开发实例-Web方式配置WiFi连接
  • ElasticSearch 批量插入漏数据
  • C++——类和对象之运算符重载
  • 第二阶段第一章——面向对象
  • Linux学习第33天:Linux INPUT 子系统实验(二):Linux 自带按键驱动程序的使用
  • 解决Visual Studio 2010 运行时屏幕一闪而过,无结果显示的问题
  • C++(20):为[[nodiscard]]提供提示信息
  • hi3518ev200 从sd卡启动rootfs
  • [BUUCTF NewStar 2023] week5 Crypto/pwn