Skip to content

Infer return type of parameterized static factory methods [SPR-9493] #14127

Closed

Description

@spring-projects-issues

Sam Brannen opened SPR-9493 and commented

Overview

Spring users often run into issues with autowiring by type for beans that are defined in XML configuration using a factory-method that is parameterized.

Although this situation arrises frequently when using dynamic mocks to replace production-specific beans in tests, this situation is not particular to tests or mocks. One can also have parameterized factory methods for generating proxies or dynamic implementations of components in production code.

Specifically, if a factory-method is parameterized (i.e., the method itself, not the enclosing class or interface), Spring always predicts the return type to be Object, even if the type can be explicitly inferred from the method signature and supplied arguments (which are available in the bean definition).

Note, however, that the order in which beans are defined plays a role here. If the bean created by the factory is instantiated by the Spring container before the autowired dependent, then there is no issue, since the concrete type of the factory-created bean is already known.

Problems arise when the ordering is reversed: if the autowired dependent bean is created before the factory-created bean is created, then the concrete type of the factory-created bean is not yet known (i.e., it will be predicted to be simply Object). Consequently, autowiring by type will fail. Similarly, a call to getBeansOfType(<type of factory-created bean>\) on the BeanFactory or ApplicationContext will also fail to return the factory-created bean if it has not yet been created.


Dynamic Mock Example

Consider a parameterized factory-method declaration such as EasyMock's createMock() method which has the following signature.

public static <T> T createMock(Class<T> toMock)

Ideally Spring should be able to predict the type T before the factory method is invoked. However, as of Spring 3.1, the predicted type is unfortunately Object instead of T. For details, see the implementation of the getTypeForFactoryMethod() method in AbstractAutowireCapableBeanFactory. In short, getTypeForFactoryMethod() does not infer the return type based on the parameterized type supplied as an argument to the factory method (i.e., Class<T> toMock in the EasyMock example). In such cases the return type is simply predicted to be Object.

Test Case

The following test case can be used to verify both the current and the proposed behavior.

With the current behavior the test passes as is.

If you comment out the three getBean() lines, the test will then fail. With the changes proposed by this issue, the test would no longer fail with those three lines removed.

@Test
public void parameterizedFactoryMethod() {
	RootBeanDefinition rbd = new RootBeanDefinition(EasyMock.class);
	rbd.setFactoryMethodName("createMock");
	rbd.getConstructorArgumentValues().addGenericArgumentValue(Runnable.class);

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("easyMock", rbd);

	// NOTE: commenting out the following three lines will prevent the
	// subsequent call to getBeansOfType() from finding the Runnable mock.
	Object mock = bf.getBean("easyMock");
	assertNotNull(mock);
	assertTrue(mock instanceof Runnable);

	Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
	assertEquals(1, beans.size());
}

Alternatives

In testing scenarios, most developers end up implementing their own FactoryBean that circumvents the issues outlined above by explicitly returning the mock object's type in FactoryBean.getObjectType() (e.g., in a MockitoFactoryBean, EasyMockFactoryBean, etc.). There is also an open source project called Springockito that addresses this issue for Spring and Mockito.

These are viable work-arounds in testing scenarios when you are explicitly overriding a bean definition with a dynamic mock, because in that case your test configuration is decidedly only for tests.

However, these work-arounds do not address the general need for reliable autowiring by type for beans created by a parameterized factory-method.


Analysis

If a factory method returns T and an argument to the factory method is either parameterized with Class<T> or of type T, then we should have enough information to infer the exact return type from the method metadata and bean definition.

Returning to the EasyMock example, if we pass java.lang.Runnable to the createMock() method, then in the getTypeForFactoryMethod() method in AbstractAutowireCapableBeanFactory we actually have access to all of the following information:

Description Value
Factory Class org.easymock.EasyMock
Factory Method createMock
Factory Method Generic Signature public static <T> T org.easymock.EasyMock.createMock(java.lang.Class<T>\)
Factory Method Type Parameters {T}
Factory Method Generic Return Type T
Factory Method Generic Parameter Types {java.lang.Class<T>}
Bean Definition Generic Constructor Args \[java.lang.Runnable\]

With that information we should be able to reliably predict the return type to be java.lang.Runnable.


Deliverables

  1. Add a new method to GenericTypeResolver that can accurately predict the target return type of a parameterized factory method in most use cases.
  2. Modify the getTypeForFactoryMethod() method in AbstractAutowireCapableBeanFactory so that it properly delegates to the method introduced in the previous deliverable, falling back to the current algorithm if the factory method is not parameterized.

Affects: 2.5 final, 3.0 GA, 3.1 GA

Issue Links:

1 votes, 5 watchers

Activity

  1. spring-projects-issues commented on Jun 19, 2012

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    Latest work on this topic: GitHub.

  2. spring-projects-issues commented on Jun 19, 2012

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    Pull request: #97

  3. spring-projects-issues commented on Jun 19, 2012

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    This work has been completed as described in the following comments from the corresponding GitHub commit.

    *Infer return type of parametrized factory methods*
    
    Currently, if a factory method is parameterized and the corresponding
    variable types are declared on the method itself instead of on the
    enclosing class or interface, Spring always predicts the return type to
    be Object, even if the return type can be explicitly inferred from the
    method signature and supplied arguments (which are available in the bean
    definition).
    
    This commit introduces a new resolveParameterizedReturnType() method in
    GenericTypeResolver that attempts to infer the concrete type for the
    generic return type of a given parameterized method, falling back to the
    standard return type if necessary. Furthermore,
    AbstractAutowireCapableBeanFactory now delegates to
    resolveParameterizedReturnType() when predicting the return type for
    factory methods.
    
    resolveParameterizedReturnType() is capable of inferring the concrete
    type for return type T for method signatures similar to the following.
    Such methods may potentially be static. Also, the formal argument list
    for such methods is not limited to a single argument.
    
     - public <T> T foo(Class<T> clazz)
     - public <T> T foo(Object obj, Class<T> clazz)
     - public <V, T> T foo(V obj, Class<T> clazz)
     - public <T> T foo(T obj)
    
    Issue: SPR-9493
    
  4. spring-projects-issues commented on Aug 5, 2012

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    FYI: resolveParameterizedReturnType() in GenericTypeResolver has been renamed to resolveReturnTypeForGenericMethod() in order to better reflect applicable use cases.

  5. spring-projects-issues commented on Mar 20, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Dmitry Katsubo commented

    Can somebody confirm this is working for the given scenario:

    XML:

    <bean name="mocksControl" class="org.easymock.EasyMock" factory-method="createStrictControl" />
    
    <bean id="transactionOperations"
    	factory-bean="mocksControl"
    	factory-method="createMock"
    	p:class="org.springframework.transaction.support.TransactionOperations" />
    
    <bean id="jdbcOperations"
    	factory-bean="mocksControl"
    	factory-method="createMock"
    	p:class="org.springframework.jdbc.core.JdbcOperations" />
    

    Java:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:/my-context.xml")
    public class MyTest {
    
    	@Autowired
    	private TransactionOperations		transactionOperations;
    
    	@Autowired
    	private IMocksControl			mocksControl;
    ...
    }
    

    Trace:

    Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.XXX.transactionOperations; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.transaction.support.TransactionOperations] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
    	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
    	... 41 more
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.transaction.support.TransactionOperations] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
    	... 43 more
    
    

    The problem is that GenericTypeResolver.resolveReturnTypeForGenericMethod() is passed args which are always empty for bean-based factory as constructed from mbd.getConstructorArgumentValues().getGenericArgumentValues(), but one need to take into account mbd.getPropertyValues().getPropertyValues() as well.

    Spring 3.2.2.

  6. spring-projects-issues commented on Mar 24, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    Dmitry Katsubo, this issue was concerned with static factory methods (i.e., against factory classes) and resolved that issue appropriately.

    Thus, please open a new issue requesting support for parameterized factory methods against factory beans.

    Thanks,

    Sam

  7. spring-projects-issues commented on Mar 24, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    Setting back to resolved.

  8. spring-projects-issues commented on Mar 24, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Dmitry Katsubo commented

    Sam, I have created a separate issue #15044.

    If I may add something:

  9. spring-projects-issues commented on Jun 8, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    Dmitry, you're totally right regarding #13769, and I've updated the links between all of these related issues accordingly.

    Regarding this issue's original Description, it in fact only discussed static factory methods; however, the Summary was generic. So I changed the Summary to explicitly refer to static factory methods in order to avoid any further confusion.

    Also, thanks for creating #15044!

    Cheers,

    Sam

  10. added
    in: test
    type: enhancement
    in: core
    on Jan 11, 2019
  11. added this to the 3.2 M2 milestone on Jan 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

in: corein: testtype: enhancement

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions