简介
ObjectProvider 是 Spring Framework 5.0 之后引入的一个新接口,它提供了一个灵活的方式来访问由 Spring 容器管理的 Bean。ObjectProvider 提供了一种更加类型安全的方式来查找和注入依赖项,同时还支持 Null 值的处理以及延迟初始化。
ObjectProvider 的一个主要优点是它支持延迟初始化。通过 getIfAvailableLazy() 方法,你可以获取一个懒加载的 Iterable,这意味着只有在迭代时才会触发 Bean 的初始化。
在 Spring 的配置和编程模型中,ObjectProvider 可以用于更灵活地处理依赖注入,特别是在处理可选的、延迟初始化的或条件性的依赖时。
源码
public interface ObjectProvider<T> extends ObjectFactory<T>, Iterable<T> {/*** 获取bean*/T getObject(Object... args) throws BeansException;/*** 如果容器中有一个可用的 Bean,则返回它,否则返回 null*/@NullableT getIfAvailable() throws BeansException;/*** 同上*/default T getIfAvailable(Supplier<T> defaultSupplier) throws BeansException {T dependency = getIfAvailable();return (dependency != null ? dependency : defaultSupplier.get());}/*** 判断容器中是否存在一个可用的bean*/default void ifAvailable(Consumer<T> dependencyConsumer) throws BeansException {T dependency = getIfAvailable();if (dependency != null) {dependencyConsumer.accept(dependency);}}/*** 如果容器中只有一个匹配的 Bean,则返回它;如果有多个匹配的 Bean,则抛出异常。*/@NullableT getIfUnique() throws BeansException;/*** 同上*/default T getIfUnique(Supplier<T> defaultSupplier) throws BeansException {T dependency = getIfUnique();return (dependency != null ? dependency : defaultSupplier.get());}/***判断是否是唯一*/default void ifUnique(Consumer<T> dependencyConsumer) throws BeansException {T dependency = getIfUnique();if (dependency != null) {dependencyConsumer.accept(dependency);}}/*** 获取迭代bean的迭代器*/@Overridedefault Iterator<T> iterator() {return stream().iterator();}/***获取bean的流*/default Stream<T> stream() {throw new UnsupportedOperationException("Multi element access not supported");}/*** 获取排序的流*/default Stream<T> orderedStream() {throw new UnsupportedOperationException("Ordered element access not supported");}}
示例
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Component; @Component
public class MyComponent { private final ObjectProvider<OptionalDependency> optionalDependencyProvider; public MyComponent(ObjectProvider<OptionalDependency> optionalDependencyProvider) { this.optionalDependencyProvider = optionalDependencyProvider; } public void doSomething() { OptionalDependency optionalDependency = optionalDependencyProvider.getIfAvailable(); if (optionalDependency != null) { // 使用 optionalDependency } }
}
在这个例子中,OptionalDependency 是一个可选的依赖项,MyComponent 通过 ObjectProvider 注入它,并使用 getIfAvailable() 方法在运行时检查它是否存在。如果 OptionalDependency Bean 在容器中可用,那么它将被注入并使用;否则,getIfAvailable() 将返回 null,并且 MyComponent 可以继续正常工作,而不需要这个依赖项。