此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0spring-doc.cadn.net.cn

Classpath 扫描和托管组件

本章中的大多数示例都使用 XML 来指定生成 每BeanDefinition在 Spring 容器中。上一节 (基于注释的容器配置)演示了如何提供大量配置 元数据。然而,即使在这些例子中,“基础” Bean 定义在 XML 文件中显式定义,而 Comments 仅驱动 依赖项注入。本节介绍用于隐式检测 candidate 组件。候选组件是 匹配过滤条件,并在 容器。这样就不需要使用 XML 来执行 Bean 注册。相反,您 可以使用注解(例如@Component)、AspectJ 类型表达式或您自己的表达式 自定义过滤条件,用于选择哪些类注册了 Bean 定义 容器。spring-doc.cadn.net.cn

您可以使用 Java 而不是 XML 文件来定义 bean。查看@Configuration,@Bean,@Import@DependsOnannotations 示例,了解如何 使用这些功能。spring-doc.cadn.net.cn

@Component和进一步的 Stereotype Annotations

@Repositoryannotation 是满足存储库角色或构造型(也称为数据访问对象或 DAO)的任何类的标记。用途 的标记是异常的自动转换,如 异常转换中所述spring-doc.cadn.net.cn

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-doc.cadn.net.cn

使用元注释和组合注释

Spring 提供的许多 Comments 都可以用作 自己的代码。元注释是可以应用于另一个注释的注释。 例如,@Service前面提到的 annotation 是元注释的@Component,如下例所示:spring-doc.cadn.net.cn

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component (1)
public @interface Service {

	// ...
}
1 @Component原因@Service以与@Component.

您还可以组合元注释来创建 “组合注释”。例如 这@RestController来自 Spring MVC 的注解由@Controller@ResponseBody.spring-doc.cadn.net.cn

此外,组合注释可以选择从 meta-annotations 允许自定义。当您 希望仅公开 meta-annotation 属性的子集。例如, Spring 的@SessionScope注解将范围名称硬编码为session但仍允许 自定义proxyMode.下面的清单显示了SessionScope注解:spring-doc.cadn.net.cn

@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;

}

然后,您可以使用@SessionScope而不声明proxyMode如下:spring-doc.cadn.net.cn

@Service
@SessionScope
public class SessionScopedService {
	// ...
}

您还可以覆盖proxyMode,如下例所示:spring-doc.cadn.net.cn

@Service
@SessionScope(proxyMode = ScopedProxyMode.INTERFACES)
public class SessionScopedUserService implements UserService {
	// ...
}

有关更多详细信息,请参阅 Spring Annotation Programming Model wiki 页面。spring-doc.cadn.net.cn

自动检测类并注册 Bean 定义

Spring 可以自动检测构造型 class 并注册相应的BeanDefinition实例中具有ApplicationContext.例如,以下两个类 符合此类自动检测的条件:spring-doc.cadn.net.cn

@Service
public class SimpleMovieLister {

	private MovieFinder movieFinder;

	public SimpleMovieLister(MovieFinder movieFinder) {
		this.movieFinder = movieFinder;
	}
}
@Repository
public class JpaMovieFinder implements MovieFinder {
	// implementation elided for clarity
}

要自动检测这些类并注册相应的 bean,您需要添加@ComponentScan发送到您的@Configuration类,其中basePackages属性 是这两个类的公共父包。(或者,您可以指定 包含每个类的父包的逗号或分号或空格分隔的列表。spring-doc.cadn.net.cn

@Configuration
@ComponentScan(basePackages = "org.example")
public class AppConfig  {
	// ...
}
为简洁起见,前面的示例可以使用value属性的 注解(即@ComponentScan("org.example")).

以下替代方法使用 XML:spring-doc.cadn.net.cn

<?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)。spring-doc.cadn.net.cn

在模块路径(Java Module System)上,Spring 的类路径扫描通常工作为 预期。但是,请确保您的组件类已导出到module-info描述 符。如果你希望 Spring 调用类的非公共成员,请将 确保它们已“打开”(即,它们使用opens声明而不是exports声明中的module-info描述符)。spring-doc.cadn.net.cn

此外,AutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessor在您使用 component-scan 元素。这意味着这两个组件是自动检测的,并且 连接在一起 — 所有这些都没有以 XML 形式提供任何 bean 配置元数据。spring-doc.cadn.net.cn

您可以禁用AutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessor通过包含annotation-config属性 的值为false.

使用过滤器自定义扫描

默认情况下,用@Component,@Repository,@Service,@Controller,@Configuration的 API 中,或者使用自定义注释(本身使用@Component是 唯一检测到的候选组件。但是,您可以修改和扩展此行为 通过应用自定义筛选器。将它们添加为includeFiltersexcludeFilters的属性 这@ComponentScan注解(或 AS<context:include-filter /><context:exclude-filter /><context:component-scan>元素 XML 配置)。每个滤芯都需要typeexpression属性。 下表描述了筛选选项:spring-doc.cadn.net.cn

表 1.过滤器类型
过滤器类型 示例表达式 描述

annotation (默认)spring-doc.cadn.net.cn

org.example.SomeAnnotationspring-doc.cadn.net.cn

目标组件中类型级别存在元存在的 Annotation。spring-doc.cadn.net.cn

可分配的spring-doc.cadn.net.cn

org.example.SomeClassspring-doc.cadn.net.cn

目标组件可分配给 (扩展或实现) 的类 (或接口) 。spring-doc.cadn.net.cn

AspectJspring-doc.cadn.net.cn

org.example..*Service+spring-doc.cadn.net.cn

要由目标组件匹配的 AspectJ 类型表达式。spring-doc.cadn.net.cn

正则表达式spring-doc.cadn.net.cn

org\.example\.Default.*spring-doc.cadn.net.cn

要与目标组件的类名称匹配的正则表达式。spring-doc.cadn.net.cn

习惯spring-doc.cadn.net.cn

org.example.MyTypeFilterspring-doc.cadn.net.cn

org.springframework.core.type.TypeFilter接口。spring-doc.cadn.net.cn

以下示例显示了忽略所有@Repository附注 并使用 “stub” 存储库:spring-doc.cadn.net.cn

@Configuration
@ComponentScan(basePackages = "org.example",
		includeFilters = @Filter(type = FilterType.REGEX, pattern = ".*Stub.*Repository"),
		excludeFilters = @Filter(Repository.class))
public class AppConfig {
	// ...
}

下面的清单显示了等效的 XML:spring-doc.cadn.net.cn

<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带注释的类。以下示例显示了如何执行此作:spring-doc.cadn.net.cn

@Component
public class FactoryMethodComponent {

	@Bean
	@Qualifier("public")
	public TestBean publicInstance() {
		return new TestBean("publicInstance");
	}

	public void doWork() {
		// Component method implementation omitted
	}
}

前面的类是一个 Spring 组件,其doWork()方法。但是,它还提供了一个 bean 定义,该定义具有 factory method 引用 methodpublicInstance().这@Beanannotation 标识 Factory 方法和其他 Bean 定义属性,例如通过 这@Qualifier注解。可以指定的其他方法级 Comments 包括@Scope,@Lazy和自定义限定符注释。spring-doc.cadn.net.cn

除了组件初始化的角色外,您还可以将@Lazy在标有@Autowired@Inject.在此上下文中, 它会导致注入延迟分辨率代理。但是,这种代理方法 相当有限。用于复杂的惰互,特别是组合 对于可选依赖项,我们建议ObjectProvider<MyTargetBean>相反。spring-doc.cadn.net.cn

如前所述,支持自动装配的字段和方法,并带有额外的 支持自动装配@Bean方法。以下示例显示了如何执行此作:spring-doc.cadn.net.cn

@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);
	}
}

该示例自动装配Stringmethod 参数country设置为age属性privateInstance.Spring Expression Language 元素 通过表示法定义属性的值#{ <expression> }.为@Valueannotations,则表达式解析器会预先配置为在 解析表达式文本。spring-doc.cadn.net.cn

从 Spring Framework 4.3 开始,您还可以声明InjectionPoint(或其更具体的子类:DependencyDescriptor) 更改为 访问触发当前 Bean 创建的请求注入点。 请注意,这仅适用于 bean 实例的实际创建,而不适用于 注入现有实例。因此,此功能最适合 prototype 范围的 bean。对于其他作用域,工厂方法只看到 触发在给定范围内创建新 bean 实例的注入点 (例如,触发创建惰性单例 Bean 的依赖项)。 在这种情况下,您可以谨慎使用提供的注入点元数据。 以下示例演示如何使用InjectionPoint:spring-doc.cadn.net.cn

@Component
public class FactoryMethodComponent {

	@Bean @Scope("prototype")
	public TestBean prototypeInstance(InjectionPoint injectionPoint) {
		return new TestBean("prototypeInstance for " + injectionPoint.getMember());
	}
}

@Bean方法的处理方式与它们的 Spring 中的对应项@Configuration类。区别在于@Component类没有使用 CGLIB 进行增强以拦截方法和字段的调用。 CGLIB 代理是调用@Bean方法 在@Configuration类 创建对协作对象的 Bean 元数据引用。 这些方法不是用普通的 Java 语义调用的,而是通过 container 来提供 Spring 的通常生命周期管理和代理 bean,即使通过对@Bean方法。 相反,在@Bean方法中的普通@Component类具有标准的 Java 语义,没有特殊的 CGLIB 处理或其他 约束适用。spring-doc.cadn.net.cn

您可以声明@Bean方法设置为static,允许在没有 创建其包含的 Configuration 类作为实例。这使得特别 sense 在定义后处理器 bean(例如,类型BeanFactoryPostProcessorBeanPostProcessor),因为这样的 bean 在容器的早期就被初始化了 生命周期,并且应避免在此时触发配置的其他部分。spring-doc.cadn.net.cn

对 static 的调用@Bean方法永远不会被容器拦截,即使是在@Configuration类(如本节前面所述),由于技术 限制: CGLIB 子类化只能覆盖非静态方法。因此, 直接调用另一个@Beanmethod 具有标准的 Java 语义,因此 在直接从工厂方法本身返回的独立实例中。spring-doc.cadn.net.cn

的 Java 语言可见性@Bean方法不会对 Spring 容器中生成的 bean 定义。您可以自由地声明您的 factory 方法,如您认为适合的非@Configuration类以及静态 方法。然而,常规的@Beanmethods 中的@Configuration类需要 才能被覆盖 — 也就是说,它们不能被声明为privatefinal.spring-doc.cadn.net.cn

@Bean方法也会在给定组件的基类上发现,或者 configuration 类,以及在 Java 8 上接口中声明的默认方法 由 component 或 configuration 类实现。这允许很多 灵活组合复杂的配置安排,甚至多个 从 Spring 4.2 开始,可以通过 Java 8 默认方法进行继承。spring-doc.cadn.net.cn

最后,单个类可以包含多个@Bean方法的 bean,作为多个工厂方法的安排,根据可用情况使用 运行时的依赖项。这与选择“最贪婪”的算法相同 constructor 或 factory 方法:具有 在构造时选择最大数量的 satisfiable dependencies, 类似于容器在多个@Autowired构造 函数。spring-doc.cadn.net.cn

命名自动检测到的组件

当组件在扫描过程中被自动检测时,其 Bean 名称为 由BeanNameGenerator该扫描仪已知的策略。spring-doc.cadn.net.cn

默认情况下,AnnotationBeanNameGenerator被使用。对于 Spring 构造型 Comments, 如果您通过注解的value属性,该名称将用作 相应 bean 定义中的名称。此约定也适用于 使用以下 JSR-250 和 JSR-330 注释来代替 Spring 构造型 附注:@jakarta.annotation.ManagedBean,@javax.annotation.ManagedBean,@jakarta.inject.Named@javax.inject.Named.spring-doc.cadn.net.cn

从 Spring Framework 6.1 开始,用于指定 bean 名称不再需要为value.自定义构造型注释可以 声明具有不同名称的属性(例如name) 并注释该属性 跟@AliasFor(annotation = Component.class, attribute = "value").查看源代码 声明ControllerAdvice#name()作为一个具体的例子。spring-doc.cadn.net.cn

从 Spring Framework 6.1 开始,不推荐使用基于约定的原型名称 ,并将在框架的未来版本中删除。因此,自定义 stereotype 注解必须使用@AliasFor要为value属性 在@Component.参见Repository#value()ControllerAdvice#name()有关具体示例。spring-doc.cadn.net.cn

如果无法从此类 Comments 或任何其他 Comments 派生显式 bean 名称 detected 组件(例如自定义过滤器发现的组件),则默认 bean 名称 generator 返回未大写的非限定类名。例如,如果 检测到以下组件类,则名称将为myMovieListermovieFinderImpl.spring-doc.cadn.net.cn

@Service("myMovieLister")
public class SimpleMovieLister {
	// ...
}
@Repository
public class MovieFinderImpl implements MovieFinder {
	// ...
}

如果您不想依赖默认的 bean 命名策略,则可以提供自定义的 bean 命名策略。首先,实现BeanNameGenerator接口,并确保包含默认的 no-arg 构造函数。然后,提供完整的 限定的类名,如以下示例注释 和 bean 定义显示。spring-doc.cadn.net.cn

如果由于多个自动检测到的组件具有 相同的非限定类名(即,具有相同名称但位于 不同的软件包),则可能需要配置BeanNameGenerator默认为 生成的 Bean 名称的完全限定类名。这FullyQualifiedAnnotationBeanNameGenerator位于包装中org.springframework.context.annotation可用于此类目的。
@Configuration
@ComponentScan(basePackages = "org.example", nameGenerator = MyNameGenerator.class)
public class AppConfig {
	// ...
}
<beans>
	<context:component-scan base-package="org.example"
		name-generator="org.example.MyNameGenerator" />
</beans>

作为一般规则,请考虑在使用 Comments 指定名称时,每当其他 组件可能会显式引用它。另一方面, 每当容器负责 wiring 时,自动生成的名称就足够了。spring-doc.cadn.net.cn

为自动检测的组件提供范围

与一般的 Spring 管理组件一样,默认和最常见的 autodetected components 为singleton.但是,有时您需要不同的范围 ,可由@Scope注解。您可以提供 范围,如下例所示:spring-doc.cadn.net.cn

@Scope("prototype")
@Repository
public class MovieFinderImpl implements MovieFinder {
	// ...
}
@Scope注解仅在具体的 Bean 类上被内省(对于带注解的 组件)或工厂方法(对于@Bean方法)。与 XML Bean 相比 定义,没有 bean 定义继承的概念,而继承 类级别的层次结构与元数据目的无关。

有关 Spring 上下文中特定于 Web 的范围(例如“request”或“session”)的详细信息, 请参阅 Request、Session、Application 和 WebSocket 范围。与这些范围的预构建注释一样, 您还可以使用 Spring 的元 Comments 编写自己的范围注释 方法:例如,使用@Scope("prototype"), 也可能声明自定义范围代理模式。spring-doc.cadn.net.cn

要为范围解析提供自定义策略,而不是依赖 基于注解的方法,您可以实现ScopeMetadataResolver接口。请务必包含默认的 no-arg 构造函数。然后,您可以提供 完全限定的类名,如以下示例所示 注释和 bean 定义显示:
@Configuration
@ComponentScan(basePackages = "org.example", scopeResolver = MyScopeResolver.class)
public 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,interfacestargetClass.例如 以下配置将生成标准 JDK 动态代理:spring-doc.cadn.net.cn

@Configuration
@ComponentScan(basePackages = "org.example", scopedProxy = ScopedProxyMode.INTERFACES)
public class AppConfig {
	// ...
}
<beans>
	<context:component-scan base-package="org.example" scoped-proxy="interfaces"/>
</beans>

提供带有注释的限定符元数据

@Qualifierannotation 在 Fine-tuning Annotation-based Autowiring with Qualifiers中讨论。 该部分中的示例演示了@Qualifierannotation 和 自定义限定符注释,用于在解析 autowire 时提供精细控制 候选人。因为这些示例是基于 XML Bean 定义的,所以限定符 元数据是使用qualifiermetabean元素。当依赖 Classpath 扫描 自动检测组件,则可以提供类型级 Candidate 类的注释。以下三个示例演示了这一点 技术:spring-doc.cadn.net.cn

@Component
@Qualifier("Action")
public class ActionMovieCatalog implements MovieCatalog {
	// ...
}
@Component
@Genre("Action")
public class ActionMovieCatalog implements MovieCatalog {
	// ...
}
@Component
@Offline
public class CachingMovieCatalog implements MovieCatalog {
	// ...
}
与大多数基于 Comments 的替代方案一样,请记住,Comments 元数据是 绑定到类定义本身,而 XML 的使用允许多个 bean 的 SAME 类型在其限定符元数据中提供变体,因为 元数据是按实例而不是按类提供的。

APP信息