此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0! |
Classpath 扫描和托管组件
本章中的大多数示例都使用 XML 来指定生成
每BeanDefinition
在 Spring 容器中。上一节
(基于注释的容器配置)演示了如何提供大量配置
元数据。然而,即使在这些例子中,“基础”
Bean 定义在 XML 文件中显式定义,而 Comments 仅驱动
依赖项注入。本节介绍用于隐式检测
candidate 组件。候选组件是
匹配过滤条件,并在
容器。这样就不需要使用 XML 来执行 Bean 注册。相反,您
可以使用注解(例如@Component
)、AspectJ 类型表达式或您自己的表达式
自定义过滤条件,用于选择哪些类注册了 Bean 定义
容器。
您可以使用 Java 而不是 XML 文件来定义 bean。查看 |
@Component
和进一步的 Stereotype Annotations
这@Repository
annotation 是满足存储库角色或构造型(也称为数据访问对象或 DAO)的任何类的标记。用途
的标记是异常的自动转换,如 异常转换中所述。
Spring 提供了进一步的构造型 Comments:@Component
,@Service
和@Controller
.@Component
是任何 Spring Management 组件的通用构造型。@Repository
,@Service
和@Controller
是 的特化@Component
为
更具体的使用案例(在 Persistence、Service 和 Presentation 中
层)。因此,您可以使用@Component
,但是,通过使用@Repository
,@Service
或@Controller
相反,您的类更适合通过工具或关联进行处理
与方面。例如,这些原型注释是
切入点。@Repository
,@Service
和@Controller
可能还
在 Spring Framework 的未来版本中携带其他语义。因此,如果你是
选择使用@Component
或@Service
对于您的服务层,@Service
是
显然是更好的选择。同样,如前所述,@Repository
已经
支持作为持久层中自动异常转换的标记。
使用元注释和组合注释
Spring 提供的许多 Comments 都可以用作
自己的代码。元注释是可以应用于另一个注释的注释。
例如,@Service
前面提到的 annotation 是元注释的@Component
,如下例所示:
-
Java
-
Kotlin
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component (1)
public @interface Service {
// ...
}
1 | 这@Component 原因@Service 以与@Component . |
@Target(AnnotationTarget.TYPE)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@Component (1)
annotation class Service {
// ...
}
1 | 这@Component 原因@Service 以与@Component . |
您还可以组合元注释来创建 “组合注释”。例如
这@RestController
来自 Spring MVC 的注解由@Controller
和@ResponseBody
.
此外,组合注释可以选择从
meta-annotations 允许自定义。当您
希望仅公开 meta-annotation 属性的子集。例如, Spring 的@SessionScope
注解将范围名称硬编码为session
但仍允许
自定义proxyMode
.下面的清单显示了SessionScope
注解:
-
Java
-
Kotlin
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Scope(WebApplicationContext.SCOPE_SESSION)
public @interface SessionScope {
/**
* Alias for {@link Scope#proxyMode}.
* <p>Defaults to {@link ScopedProxyMode#TARGET_CLASS}.
*/
@AliasFor(annotation = Scope.class)
ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS;
}
@Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@Scope(WebApplicationContext.SCOPE_SESSION)
annotation class SessionScope(
@get:AliasFor(annotation = Scope::class)
val proxyMode: ScopedProxyMode = ScopedProxyMode.TARGET_CLASS
)
然后,您可以使用@SessionScope
而不声明proxyMode
如下:
-
Java
-
Kotlin
@Service
@SessionScope
public class SessionScopedService {
// ...
}
@Service
@SessionScope
class SessionScopedService {
// ...
}
您还可以覆盖proxyMode
,如下例所示:
-
Java
-
Kotlin
@Service
@SessionScope(proxyMode = ScopedProxyMode.INTERFACES)
public class SessionScopedUserService implements UserService {
// ...
}
@Service
@SessionScope(proxyMode = ScopedProxyMode.INTERFACES)
class SessionScopedUserService : UserService {
// ...
}
有关更多详细信息,请参阅 Spring Annotation Programming Model wiki 页面。
自动检测类并注册 Bean 定义
Spring 可以自动检测构造型 class 并注册相应的BeanDefinition
实例中具有ApplicationContext
.例如,以下两个类
符合此类自动检测的条件:
-
Java
-
Kotlin
@Service
public class SimpleMovieLister {
private MovieFinder movieFinder;
public SimpleMovieLister(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}
@Service
class SimpleMovieLister(private val movieFinder: MovieFinder)
-
Java
-
Kotlin
@Repository
public class JpaMovieFinder implements MovieFinder {
// implementation elided for clarity
}
@Repository
class JpaMovieFinder : MovieFinder {
// implementation elided for clarity
}
要自动检测这些类并注册相应的 bean,您需要添加@ComponentScan
发送到您的@Configuration
类,其中basePackages
属性
是这两个类的公共父包。(或者,您可以指定
包含每个类的父包的逗号或分号或空格分隔的列表。
-
Java
-
Kotlin
@Configuration
@ComponentScan(basePackages = "org.example")
public class AppConfig {
// ...
}
@Configuration
@ComponentScan(basePackages = ["org.example"])
class AppConfig {
// ...
}
为简洁起见,前面的示例可以使用value 属性的
注解(即@ComponentScan("org.example") ). |
以下替代方法使用 XML:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.example"/>
</beans>
的使用<context:component-scan> 隐式启用<context:annotation-config> .通常不需要包含<context:annotation-config> 元素<context:component-scan> . |
扫描 classpath 包需要存在相应的目录 条目。使用 Ant 构建 JAR 时,请确保不要 激活 JAR 任务的 files-only 开关。此外,类路径目录可能不是 在某些环境中根据安全策略公开,例如,独立应用程序 JDK 1.7.0_45 及更高版本(需要在清单中设置“Trusted-Library”——请参阅 stackoverflow.com/questions/19394570/java-jre-7u45-breaks-classloader-getresources)。 在模块路径(Java Module System)上,Spring 的类路径扫描通常工作为
预期。但是,请确保您的组件类已导出到 |
此外,AutowiredAnnotationBeanPostProcessor
和CommonAnnotationBeanPostProcessor
在您使用
component-scan 元素。这意味着这两个组件是自动检测的,并且
连接在一起 — 所有这些都没有以 XML 形式提供任何 bean 配置元数据。
您可以禁用AutowiredAnnotationBeanPostProcessor 和CommonAnnotationBeanPostProcessor 通过包含annotation-config 属性
的值为false . |
使用过滤器自定义扫描
默认情况下,用@Component
,@Repository
,@Service
,@Controller
,@Configuration
的 API 中,或者使用自定义注释(本身使用@Component
是
唯一检测到的候选组件。但是,您可以修改和扩展此行为
通过应用自定义筛选器。将它们添加为includeFilters
或excludeFilters
的属性
这@ComponentScan
注解(或 AS<context:include-filter />
或<context:exclude-filter />
的<context:component-scan>
元素
XML 配置)。每个滤芯都需要type
和expression
属性。
下表描述了筛选选项:
过滤器类型 | 示例表达式 | 描述 |
---|---|---|
annotation (默认) |
|
目标组件中类型级别存在或元存在的 Annotation。 |
可分配的 |
|
目标组件可分配给 (扩展或实现) 的类 (或接口) 。 |
AspectJ |
|
要由目标组件匹配的 AspectJ 类型表达式。 |
正则表达式 |
|
要与目标组件的类名称匹配的正则表达式。 |
习惯 |
|
的 |
以下示例显示了忽略所有@Repository
附注
并使用 “stub” 存储库:
-
Java
-
Kotlin
@Configuration
@ComponentScan(basePackages = "org.example",
includeFilters = @Filter(type = FilterType.REGEX, pattern = ".*Stub.*Repository"),
excludeFilters = @Filter(Repository.class))
public class AppConfig {
// ...
}
@Configuration
@ComponentScan(basePackages = ["org.example"],
includeFilters = [Filter(type = FilterType.REGEX, pattern = [".*Stub.*Repository"])],
excludeFilters = [Filter(Repository::class)])
class AppConfig {
// ...
}
下面的清单显示了等效的 XML:
<beans>
<context:component-scan base-package="org.example">
<context:include-filter type="regex"
expression=".*Stub.*Repository"/>
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
</beans>
您还可以通过设置useDefaultFilters=false 在
注解或通过提供use-default-filters="false" 作为<component-scan/> 元素。这实际上禁用了类的自动检测
annotated 或 meta-annotated with@Component ,@Repository ,@Service ,@Controller ,@RestController 或@Configuration . |
在组件中定义 Bean 元数据
Spring 组件还可以向容器提供 bean 定义元数据。你可以做
this 具有相同的@Bean
用于定义 Bean 元数据的注释@Configuration
带注释的类。以下示例显示了如何执行此作:
-
Java
-
Kotlin
@Component
public class FactoryMethodComponent {
@Bean
@Qualifier("public")
public TestBean publicInstance() {
return new TestBean("publicInstance");
}
public void doWork() {
// Component method implementation omitted
}
}
@Component
class FactoryMethodComponent {
@Bean
@Qualifier("public")
fun publicInstance() = TestBean("publicInstance")
fun doWork() {
// Component method implementation omitted
}
}
前面的类是一个 Spring 组件,其doWork()
方法。但是,它还提供了一个 bean 定义,该定义具有 factory
method 引用 methodpublicInstance()
.这@Bean
annotation 标识
Factory 方法和其他 Bean 定义属性,例如通过
这@Qualifier
注解。可以指定的其他方法级 Comments 包括@Scope
,@Lazy
和自定义限定符注释。
除了组件初始化的角色外,您还可以将 |
如前所述,支持自动装配的字段和方法,并带有额外的
支持自动装配@Bean
方法。以下示例显示了如何执行此作:
-
Java
-
Kotlin
@Component
public class FactoryMethodComponent {
private static int i;
@Bean
@Qualifier("public")
public TestBean publicInstance() {
return new TestBean("publicInstance");
}
// use of a custom qualifier and autowiring of method parameters
@Bean
protected TestBean protectedInstance(
@Qualifier("public") TestBean spouse,
@Value("#{privateInstance.age}") String country) {
TestBean tb = new TestBean("protectedInstance", 1);
tb.setSpouse(spouse);
tb.setCountry(country);
return tb;
}
@Bean
private TestBean privateInstance() {
return new TestBean("privateInstance", i++);
}
@Bean
@RequestScope
public TestBean requestScopedInstance() {
return new TestBean("requestScopedInstance", 3);
}
}
@Component
class FactoryMethodComponent {
companion object {
private var i: Int = 0
}
@Bean
@Qualifier("public")
fun publicInstance() = TestBean("publicInstance")
// use of a custom qualifier and autowiring of method parameters
@Bean
protected fun protectedInstance(
@Qualifier("public") spouse: TestBean,
@Value("#{privateInstance.age}") country: String) = TestBean("protectedInstance", 1).apply {
this.spouse = spouse
this.country = country
}
@Bean
private fun privateInstance() = TestBean("privateInstance", i++)
@Bean
@RequestScope
fun requestScopedInstance() = TestBean("requestScopedInstance", 3)
}
该示例自动装配String
method 参数country
设置为age
属性privateInstance
.Spring Expression Language 元素
通过表示法定义属性的值#{ <expression> }
.为@Value
annotations,则表达式解析器会预先配置为在
解析表达式文本。
从 Spring Framework 4.3 开始,您还可以声明InjectionPoint
(或其更具体的子类:DependencyDescriptor
) 更改为
访问触发当前 Bean 创建的请求注入点。
请注意,这仅适用于 bean 实例的实际创建,而不适用于
注入现有实例。因此,此功能最适合
prototype 范围的 bean。对于其他作用域,工厂方法只看到
触发在给定范围内创建新 bean 实例的注入点
(例如,触发创建惰性单例 Bean 的依赖项)。
在这种情况下,您可以谨慎使用提供的注入点元数据。
以下示例演示如何使用InjectionPoint
:
-
Java
-
Kotlin
@Component
public class FactoryMethodComponent {
@Bean @Scope("prototype")
public TestBean prototypeInstance(InjectionPoint injectionPoint) {
return new TestBean("prototypeInstance for " + injectionPoint.getMember());
}
}
@Component
class FactoryMethodComponent {
@Bean
@Scope("prototype")
fun prototypeInstance(injectionPoint: InjectionPoint) =
TestBean("prototypeInstance for ${injectionPoint.member}")
}
这@Bean
方法的处理方式与它们的
Spring 中的对应项@Configuration
类。区别在于@Component
类没有使用 CGLIB 进行增强以拦截方法和字段的调用。
CGLIB 代理是调用@Bean
方法
在@Configuration
类 创建对协作对象的 Bean 元数据引用。
这些方法不是用普通的 Java 语义调用的,而是通过
container 来提供 Spring 的通常生命周期管理和代理
bean,即使通过对@Bean
方法。
相反,在@Bean
方法中的普通@Component
类具有标准的 Java 语义,没有特殊的 CGLIB 处理或其他
约束适用。
您可以声明 对 static 的调用 的 Java 语言可见性
最后,单个类可以包含多个 |
命名自动检测到的组件
当组件在扫描过程中被自动检测时,其 Bean 名称为
由BeanNameGenerator
该扫描仪已知的策略。
默认情况下,AnnotationBeanNameGenerator
被使用。对于 Spring 构造型 Comments,
如果您通过注解的value
属性,该名称将用作
相应 bean 定义中的名称。此约定也适用于
使用以下 JSR-250 和 JSR-330 注释来代替 Spring 构造型
附注:@jakarta.annotation.ManagedBean
,@javax.annotation.ManagedBean
,@jakarta.inject.Named
和@javax.inject.Named
.
从 Spring Framework 6.1 开始,用于指定
bean 名称不再需要为value
.自定义构造型注释可以
声明具有不同名称的属性(例如name
) 并注释该属性
跟@AliasFor(annotation = Component.class, attribute = "value")
.查看源代码
声明ControllerAdvice#name()
作为一个具体的例子。
从 Spring Framework 6.1 开始,不推荐使用基于约定的原型名称
,并将在框架的未来版本中删除。因此,自定义 stereotype
注解必须使用 |
如果无法从此类 Comments 或任何其他 Comments 派生显式 bean 名称
detected 组件(例如自定义过滤器发现的组件),则默认 bean 名称
generator 返回未大写的非限定类名。例如,如果
检测到以下组件类,则名称将为myMovieLister
和movieFinderImpl
.
-
Java
-
Kotlin
@Service("myMovieLister")
public class SimpleMovieLister {
// ...
}
@Service("myMovieLister")
class SimpleMovieLister {
// ...
}
-
Java
-
Kotlin
@Repository
public class MovieFinderImpl implements MovieFinder {
// ...
}
@Repository
class MovieFinderImpl : MovieFinder {
// ...
}
如果您不想依赖默认的 bean 命名策略,则可以提供自定义的
bean 命名策略。首先,实现BeanNameGenerator
接口,并确保包含默认的 no-arg 构造函数。然后,提供完整的
限定的类名,如以下示例注释
和 bean 定义显示。
如果由于多个自动检测到的组件具有
相同的非限定类名(即,具有相同名称但位于
不同的软件包),则可能需要配置BeanNameGenerator 默认为
生成的 Bean 名称的完全限定类名。这FullyQualifiedAnnotationBeanNameGenerator 位于包装中org.springframework.context.annotation 可用于此类目的。 |
-
Java
-
Kotlin
@Configuration
@ComponentScan(basePackages = "org.example", nameGenerator = MyNameGenerator.class)
public class AppConfig {
// ...
}
@Configuration
@ComponentScan(basePackages = ["org.example"], nameGenerator = MyNameGenerator::class)
class AppConfig {
// ...
}
<beans>
<context:component-scan base-package="org.example"
name-generator="org.example.MyNameGenerator" />
</beans>
作为一般规则,请考虑在使用 Comments 指定名称时,每当其他 组件可能会显式引用它。另一方面, 每当容器负责 wiring 时,自动生成的名称就足够了。
为自动检测的组件提供范围
与一般的 Spring 管理组件一样,默认和最常见的
autodetected components 为singleton
.但是,有时您需要不同的范围
,可由@Scope
注解。您可以提供
范围,如下例所示:
-
Java
-
Kotlin
@Scope("prototype")
@Repository
public class MovieFinderImpl implements MovieFinder {
// ...
}
@Scope("prototype")
@Repository
class MovieFinderImpl : MovieFinder {
// ...
}
@Scope 注解仅在具体的 Bean 类上被内省(对于带注解的
组件)或工厂方法(对于@Bean 方法)。与 XML Bean 相比
定义,没有 bean 定义继承的概念,而继承
类级别的层次结构与元数据目的无关。 |
有关 Spring 上下文中特定于 Web 的范围(例如“request”或“session”)的详细信息,
请参阅 Request、Session、Application 和 WebSocket 范围。与这些范围的预构建注释一样,
您还可以使用 Spring 的元 Comments 编写自己的范围注释
方法:例如,使用@Scope("prototype")
,
也可能声明自定义范围代理模式。
要为范围解析提供自定义策略,而不是依赖
基于注解的方法,您可以实现ScopeMetadataResolver 接口。请务必包含默认的 no-arg 构造函数。然后,您可以提供
完全限定的类名,如以下示例所示
注释和 bean 定义显示: |
-
Java
-
Kotlin
@Configuration
@ComponentScan(basePackages = "org.example", scopeResolver = MyScopeResolver.class)
public class AppConfig {
// ...
}
@Configuration
@ComponentScan(basePackages = ["org.example"], scopeResolver = MyScopeResolver::class)
class AppConfig {
// ...
}
<beans>
<context:component-scan base-package="org.example" scope-resolver="org.example.MyScopeResolver"/>
</beans>
当使用某些非单例作用域时,可能需要为
scoped 对象。原因在 Scoped Bean as Dependencies 中进行了描述。
为此,component-scan 上提供了 scoped-proxy 属性
元素。三个可能的值是:no
,interfaces
和targetClass
.例如
以下配置将生成标准 JDK 动态代理:
-
Java
-
Kotlin
@Configuration
@ComponentScan(basePackages = "org.example", scopedProxy = ScopedProxyMode.INTERFACES)
public class AppConfig {
// ...
}
@Configuration
@ComponentScan(basePackages = ["org.example"], scopedProxy = ScopedProxyMode.INTERFACES)
class AppConfig {
// ...
}
<beans>
<context:component-scan base-package="org.example" scoped-proxy="interfaces"/>
</beans>
提供带有注释的限定符元数据
这@Qualifier
annotation 在 Fine-tuning Annotation-based Autowiring with Qualifiers中讨论。
该部分中的示例演示了@Qualifier
annotation 和
自定义限定符注释,用于在解析 autowire 时提供精细控制
候选人。因为这些示例是基于 XML Bean 定义的,所以限定符
元数据是使用qualifier
或meta
的bean
元素。当依赖 Classpath 扫描
自动检测组件,则可以提供类型级
Candidate 类的注释。以下三个示例演示了这一点
技术:
-
Java
-
Kotlin
@Component
@Qualifier("Action")
public class ActionMovieCatalog implements MovieCatalog {
// ...
}
@Component
@Qualifier("Action")
class ActionMovieCatalog : MovieCatalog
-
Java
-
Kotlin
@Component
@Genre("Action")
public class ActionMovieCatalog implements MovieCatalog {
// ...
}
@Component
@Genre("Action")
class ActionMovieCatalog : MovieCatalog {
// ...
}
-
Java
-
Kotlin
@Component
@Offline
public class CachingMovieCatalog implements MovieCatalog {
// ...
}
@Component
@Offline
class CachingMovieCatalog : MovieCatalog {
// ...
}
与大多数基于 Comments 的替代方案一样,请记住,Comments 元数据是 绑定到类定义本身,而 XML 的使用允许多个 bean 的 SAME 类型在其限定符元数据中提供变体,因为 元数据是按实例而不是按类提供的。 |