簡介
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 可以繼續正常工作,而不需要這個依賴項。