--- spring 自动装配 ---

Spring Boot 的组件扫描机制默认会以 @SpringBootApplication 注解标记的类作为起点,递归扫描当前包及其子包下所有含有 Spring 管理注解(如 @Component、@Service 等)的类,并将它们注册到 IOC 容器中。这样,在程序的其他地方便可以通过 @Autowired 等注解进行依赖注入。

但这种机制也带来一个常见问题:如果要注入的类并不在 @SpringBootApplication 所在包的扫描路径下------例如一个完全独立的第三方类或位于其他模块中的类------Spring 在启动时就不会将其纳入容器管理。此时如果尝试自动注入,便会抛出 NoSuchBeanDefinitionException 异常,提示找不到对应的 Bean。

spring为了解决这个问题,提供了三种方法来将外部的类加载到spring ioc容器中

@ComponentScan() 指定扫描路径

复制代码
@ComponentScan("com.hadage")  

@Import() 单独指定要管理的具体类

复制代码
@Import(ValidationTest.class)

以上方法也都需要在项目总修改源码,而且可读性也比较差,毕竟代码一多看着就头大了

而还有一个更加通用的方法

在resource中添加META-INF.spring包,这个包下创建名字为org.springframework.boot.autoconfigure. AutoConfiguration.imports的文件,在这个文件中加入需要管理的类的路径

复制代码
com.bitejiuyeke.bitecommonsecurity.handler.GlobalExceptionHandler

包的具体

相关推荐
shuair1 天前
redis缓存预热、缓存击穿、缓存穿透、缓存雪崩
redis·spring·缓存
计算机程序设计小李同学1 天前
基于 Spring Boot + Vue 的龙虾专营店管理系统的设计与实现
java·spring boot·后端·spring·vue
qq_12498707531 天前
基于Java Web的城市花园小区维修管理系统的设计与实现(源码+论文+部署+安装)
java·开发语言·前端·spring boot·spring·毕业设计·计算机毕业设计
Chasmれ1 天前
Spring Boot 1.x(基于Spring 4)中使用Java 8实现Token
java·spring boot·spring
计算机学姐1 天前
基于SpringBoot的校园社团管理系统
java·vue.js·spring boot·后端·spring·信息可视化·推荐算法
落霞的思绪1 天前
Spring AI Alibaba 集成 Redis 向量数据库实现 RAG 与记忆功能
java·spring·rag·springai
Remember_9931 天前
MySQL 索引详解:从原理到实战优化
java·数据库·mysql·spring·http·adb·面试
勤奋的小王同学~1 天前
SpringMVC
java·spring·mvc
露天赏雪1 天前
JDK8 的入门避坑指南
java·服务器·windows·spring boot·后端·spring·性能优化
wxin_VXbishe1 天前
springboot旅游信息管理系统-计算机毕业设计源码21675
java·c++·spring boot·python·spring·django·php