Spring的自动装配,组件扫描
Spring提供了三种主要的装配机制:
XML 中进行显式配置。
Java 中进行显式配置。
隐式的 bean 发现机制和自动装配。
Spring 从两个角度来实现自动化装配:
组件扫描( component scanning ): Spring 会自动发现应用上下文中所创建的 bean 。
自动装配( autowiring ): Spring 自动满足 bean 之间的依赖。
我们一般使用 @Autowired
注解自动装配 bean,要想把类标识成可用于 @Autowired
注解自动装配的 bean 的类,采用以下注解可实现:
@Component
:通用的注解,可标注任意类为Spring
组件。如果一个Bean不知道属于哪个层,可以使用@Component
注解标注。@Repository
: 对应持久层即 Dao 层,主要用于数据库相关操作。@Service
: 对应服务层,主要涉及一些复杂的逻辑,需要用到 Dao层。@Controller
: 对应 Spring MVC 控制层,主要用户接受用户请求并调用 Service 层返回数据给前端页面。
组件扫描方式:
1、@ComponentScan 注解启用了组件扫描
@ComponentScan用于类或接口上主要是指定扫描路径,spring会把指定路径下带有指定注解的类自动装配到bean容器里。
会被自动装配的注解包括@Controller、@Service、@Component、@Repository等等。其作用等同于<context:component-scan base-package="com.maple.learn" />配置
2、 XML 启用组件扫描
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <context:component-scan base- package = "com.wjx.betalot" <!-- 扫描的基本包路径 --> annotation-config= "true" <!-- 是否激活属性注入注解 --> name-generator= "org.springframework.context.annotation.AnnotationBeanNameGenerator" <!-- Bean的ID策略生成器 --> resource-pattern= "**/*.class" <!-- 对资源进行筛选的正则表达式,这边是个大的范畴,具体细分在include-filter与exclude-filter中进行 --> scope-resolver= "org.springframework.context.annotation.AnnotationScopeMetadataResolver" <!-- scope解析器 ,与scoped-proxy只能同时配置一个 --> scoped-proxy= "no" <!-- scope代理,与scope-resolver只能同时配置一个 --> use- default -filters= "false" <!-- 是否使用默认的过滤器,默认值 true --> > <!-- 注意:若使用include-filter去定制扫描内容,要在use- default -filters= "false" 的情况下,不然会“失效”,被默认的过滤机制所覆盖 --> <!-- annotation是对注解进行扫描 --> <context:include-filter type= "annotation" expression= "org.springframework.stereotype.Component" /> <!-- assignable是对类或接口进行扫描 --> <context:include-filter type= "assignable" expression= "com.wjx.betalot.performer.Performer" /> <context:include-filter type= "assignable" expression= "com.wjx.betalot.performer.impl.Sonnet" /> <!-- 注意:在use- default -filters= "false" 的情况下,exclude-filter是针对include-filter里的内容进行排除 --> <context:exclude-filter type= "annotation" expression= "org.springframework.stereotype.Controller" /> <context:exclude-filter type= "assignable" expression= "com.wjx.betalot.performer.impl.RainPoem" /> <context:exclude-filter type= "regex" expression= ".service.*" /> </context:component-scan> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)