概述
ObjectProvider
直譯就是對象提供者;
平時從spring
中獲取bean
都是調用beanFactory.getBean()
方法,如果bean不存在則會直接拋異常;
從spring 4.3
開始引入了org.springframework.beans.factory.ObjectProvider
接口,其提供了若干的方法,可以更松散的獲取bean
.
BeanFactory
中也有定義返回值是ObjectProvider
的相關方法;
ObjectProvider方法解釋
直接引用一波網上現成的翻譯
public interface ObjectProvider<T> extends ObjectFactory<T>, Iterable<T> {// 返回指定類型的bean, 如果容器中不存在, 拋出NoSuchBeanDefinitionException異常// 如果容器中有多個此類型的bean, 拋出NoUniqueBeanDefinitionException異常T getObject(Object... args) throws BeansException;// 如果指定類型的bean注冊到容器中, 返回 bean 實例, 否則返回 null@NullableT getIfAvailable() throws BeansException;// 如果返回對象不存在,則進行回調,回調對象由Supplier傳入default T getIfAvailable(Supplier<T> defaultSupplier) throws BeansException {T dependency = getIfAvailable();return (dependency != null ? dependency : defaultSupplier.get());}// 消費對象的一個實例(可能是共享的或獨立的),如果存在通過Consumer回調消耗目標對象。default void ifAvailable(Consumer<T> dependencyConsumer) throws BeansException {T dependency = getIfAvailable();if (dependency != null) {dependencyConsumer.accept(dependency);}}// 如果不可用或不唯一(沒有指定primary)則返回null。否則,返回對象。@NullableT getIfUnique() throws BeansException;// 如果存在唯一對象,則調用Supplier的回調函數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);}}// 返回符合條件的對象的Iterator,沒有特殊順序保證(一般為注冊順序)@Overridedefault Iterator<T> iterator() {return stream().iterator();}// 返回符合條件對象的連續的Stream,沒有特殊順序保證(一般為注冊順序)default Stream<T> stream() {throw new UnsupportedOperationException("Multi element access not supported");}// 返回符合條件對象的連續的Stream。在標注Spring應用上下文中采用@Order注解或實現Order接口的順序default Stream<T> orderedStream() {throw new UnsupportedOperationException("Ordered element access not supported");}
}
參考文章
https://www.cnblogs.com/secbro/p/11974729.html