最近在看一段源码的时候,大量出现了ObjectProvider这样的接口。跟进查看,然后大概做个了解。
ObjectProvider
ObjectProvider接口,继承ObjectFactory,里面的方法如下:
public interface ObjectProvider<T> extends ObjectFactory<T> {
/**
* Return an instance (possibly shared or independent) of the object
* managed by this factory.
* <p>Allows for specifying explicit construction arguments, along the
* lines of {@link BeanFactory#getBean(String, Object...)}.
* @param args arguments to use when creating a corresponding instance
* @return an instance of the bean
* @throws BeansException in case of creation errors
* @see #getObject()
*/
T getObject(Object... args) throws BeansException;
/**
* Return an instance (possibly shared or independent) of the object
* managed by this factory.
* @return an instance of the bean, or {@code null} if not available
* @throws BeansException in case of creation errors
* @see #getObject()
*/
T getIfAvailable() throws BeansException;
/**
* Return an instance (possibly shared or independent) of the object
* managed by this factory.
* @return an instance of the bean, or {@code null} if not available or
* not unique (i.e. multiple candidates found with none marked as primary)
* @throws BeansException in case of creation errors
* @see #getObject()
*/
T getIfUnique() throws BeansException;
}
根据方法和注释,大概知道他的用处。
查看ObjectProvider的继承关系,只有一个DependencyObjectProvider
在使用。跟进去查看,大概了解了起使用场景,他的解释:
Serializable ObjectFactory/ObjectProvider for lazy resolution of a dependency.
。他的大概意图就是用于延迟延迟加载使用。在查看很多Spring的代码时候,用处大多数是用于在构造方法上进行使用。
- @Autowire注解可以用于字段,setter,构造函数
- 但是构造函数有多个参数的时候,@Autowire就不知道怎么办了。
- Spring 4.x 以后,如果构造方法的参数只有一个,那么会自动加入@autowire进行依赖注入
- 同时,针对多个参数的情况,可以只用ObjectProvider进行包裹,在构造函数中,由编码的方式进行延迟调用。
Spring使用的代码段,
DefaultListableBeanFactory
@Override
public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName,
Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
if (javaUtilOptionalClass == descriptor.getDependencyType()) {
return new OptionalDependencyFactory().createOptionalDependency(descriptor, requestingBeanName);
}
else if (ObjectFactory.class == descriptor.getDependencyType() ||
ObjectProvider.class == descriptor.getDependencyType()) {
return new DependencyObjectProvider(descriptor, requestingBeanName);
}
使用场景:
@Service
public class FooService {
private final FooRepository repository;
public FooService(ObjectProvider<FooRepository> repositoryProvider) {
this.repository = repositoryProvider.getIfUnique();
}
}
其实深入观察,它实际上调用了的就是DefaultListableBeanFactory
去解析依赖的Bean。