Support for SmartObjectFactory injection points with programmatic optionality and lenient not-unique handling

Issue: SPR-13943
This commit is contained in:
Juergen Hoeller 2016-02-12 17:45:25 +01:00
parent b79e8a5cbc
commit 343bb2f130
4 changed files with 217 additions and 3 deletions

View File

@ -0,0 +1,49 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory;
import org.springframework.beans.BeansException;
/**
* A variant of {@link ObjectFactory} designed specifically for injection points,
* allowing for programmatic optionality and lenient not-unique handling.
*
* @author Juergen Hoeller
* @since 4.3
*/
public interface SmartObjectFactory<T> extends ObjectFactory<T> {
/**
* 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;
}

View File

@ -23,7 +23,10 @@ import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.core.GenericCollectionTypeResolver;
import org.springframework.core.GenericTypeResolver;
import org.springframework.core.MethodParameter;
@ -180,6 +183,23 @@ public class DependencyDescriptor implements Serializable {
return this.eager;
}
/**
* Resolve the specified not-unique scenario: by default,
* throwing a {@link NoUniqueBeanDefinitionException}.
* <p>Subclasses may override this to select one of the instances or
* to opt out with no result at all through returning {@code null}.
* @param type the requested bean type
* @param matchingBeans a map of bean names and corresponding bean
* instances which have been pre-selected for the given type
* (qualifiers etc already applied)
* @return a bean instance to proceed with, or {@code null} for none
* @throws BeansException in case of the not-unique scenario being fatal
* @since 4.3
*/
public Object resolveNotUnique(Class<?> type, Map<String, Object> matchingBeans) throws BeansException {
throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet());
}
/**
* Increase this descriptor's nesting level.

View File

@ -59,6 +59,7 @@ import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.SmartFactoryBean;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.SmartObjectFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
@ -1006,7 +1007,8 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
if (descriptor.getDependencyType().equals(javaUtilOptionalClass)) {
return new OptionalDependencyFactory().createOptionalDependency(descriptor, beanName);
}
else if (ObjectFactory.class == descriptor.getDependencyType()) {
else if (ObjectFactory.class == descriptor.getDependencyType() ||
SmartObjectFactory.class == descriptor.getDependencyType()) {
return new DependencyObjectFactory(descriptor, beanName);
}
else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
@ -1054,7 +1056,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
String primaryBeanName = determineAutowireCandidate(matchingBeans, descriptor);
if (primaryBeanName == null) {
if (multipleBeans == NOT_MULTIPLE_BEANS || descriptor.isRequired()) {
throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet());
return descriptor.resolveNotUnique(type, matchingBeans);
}
else {
// In case of an optional Collection/Map, silently ignore a non-unique case:
@ -1474,7 +1476,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
/**
* Serializable ObjectFactory for lazy resolution of a dependency.
*/
private class DependencyObjectFactory implements ObjectFactory<Object>, Serializable {
private class DependencyObjectFactory implements SmartObjectFactory<Object>, Serializable {
private final DependencyDescriptor descriptor;
@ -1498,6 +1500,42 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
return doResolveDependency(this.descriptor, this.beanName, null, null);
}
}
@Override
public Object getIfAvailable() throws BeansException {
if (this.optional) {
return new OptionalDependencyFactory().createOptionalDependency(this.descriptor, this.beanName);
}
else {
DependencyDescriptor descriptorToUse = new DependencyDescriptor(descriptor) {
@Override
public boolean isRequired() {
return false;
}
};
return doResolveDependency(descriptorToUse, this.beanName, null, null);
}
}
@Override
public Object getIfUnique() throws BeansException {
DependencyDescriptor descriptorToUse = new DependencyDescriptor(descriptor) {
@Override
public boolean isRequired() {
return false;
}
@Override
public Object resolveNotUnique(Class<?> type, Map<String, Object> matchingBeans) {
return null;
}
};
if (this.optional) {
return new OptionalDependencyFactory().createOptionalDependency(descriptorToUse, this.beanName);
}
else {
return doResolveDependency(descriptorToUse, this.beanName, null, null);
}
}
}

View File

@ -41,7 +41,10 @@ import org.mockito.Mockito;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.SmartObjectFactory;
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
@ -1044,6 +1047,91 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.destroySingletons();
}
@Test
public void testSmartObjectFactoryInjection() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SmartObjectFactoryInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
SmartObjectFactoryInjectionBean bean = (SmartObjectFactoryInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean());
assertSame(bf.getBean("testBean"), bean.getOptionalTestBean());
assertSame(bf.getBean("testBean"), bean.getUniqueTestBean());
bf.destroySingletons();
}
@Test
public void testSmartObjectFactoryInjectionWithTargetNotAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SmartObjectFactoryInjectionBean.class));
SmartObjectFactoryInjectionBean bean = (SmartObjectFactoryInjectionBean) bf.getBean("annotatedBean");
try {
bean.getTestBean();
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
assertNull(bean.getOptionalTestBean());
assertNull(bean.getUniqueTestBean());
bf.destroySingletons();
}
@Test
public void testSmartObjectFactoryInjectionWithTargetNotUnique() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SmartObjectFactoryInjectionBean.class));
bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class));
bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
SmartObjectFactoryInjectionBean bean = (SmartObjectFactoryInjectionBean) bf.getBean("annotatedBean");
try {
bean.getTestBean();
fail("Should have thrown NoUniqueBeanDefinitionException");
}
catch (NoUniqueBeanDefinitionException ex) {
// expected
}
try {
bean.getOptionalTestBean();
fail("Should have thrown NoUniqueBeanDefinitionException");
}
catch (NoUniqueBeanDefinitionException ex) {
// expected
}
assertNull(bean.getUniqueTestBean());
bf.destroySingletons();
}
@Test
public void testSmartObjectFactoryInjectionWithTargetPrimary() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SmartObjectFactoryInjectionBean.class));
RootBeanDefinition tb1 = new RootBeanDefinition(TestBean.class);
tb1.setPrimary(true);
bf.registerBeanDefinition("testBean1", tb1);
bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
SmartObjectFactoryInjectionBean bean = (SmartObjectFactoryInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean1"), bean.getTestBean());
assertSame(bf.getBean("testBean1"), bean.getOptionalTestBean());
assertSame(bf.getBean("testBean1"), bean.getUniqueTestBean());
bf.destroySingletons();
}
@Test
public void testCustomAnnotationRequiredFieldResourceInjection() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
@ -2461,6 +2549,25 @@ public class AutowiredAnnotationBeanPostProcessorTests {
}
public static class SmartObjectFactoryInjectionBean {
@Autowired
private SmartObjectFactory<TestBean> testBeanFactory;
public TestBean getTestBean() {
return this.testBeanFactory.getObject();
}
public TestBean getOptionalTestBean() {
return this.testBeanFactory.getIfAvailable();
}
public TestBean getUniqueTestBean() {
return this.testBeanFactory.getIfUnique();
}
}
public static class CustomAnnotationRequiredFieldResourceInjectionBean {
@MyAutowired(optional = false)