Skip to content

Return type prediction for generic factory method fails if type conversion of method arguments is necessary [SPR-10411] #15044

Closed

Description

@spring-projects-issues

Dmitry Katsubo opened SPR-10411 and commented

Overview

The following scenario does not work.

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

Analysis

See comments below.


Affects: 3.2.2

Attachments:

Issue Links:

Referenced from: commits 8fdc7d4, b913578, b305f00, e86e182, 8b1927f

Activity

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

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

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

    Actually, you should be passing arguments to a factory method via <constructor-arg>, not <parameter>.

    For example, if I change your p:class declaration to c:_, it works fine for me.

    Whereas, if I run my test using your p:class declaration, I get the following error:

    java.lang.IllegalStateException: Failed to load ApplicationContext
    ...
    
    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jdbcOperations' defined in class path resource [**********.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.lang.Class]: Ambiguous factory method argument types - did you specify the correct bean references as factory method arguments?
    	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:719)
    ...
    

    So, could you please retry your example using constructor arguments to the factory method?

    Thanks!

    Sam

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

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    For full disclosure (and since I don't plan to check this code in anywhere), here's what I used to integration test this:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xmlns:c="http://www.springframework.org/schema/c" xmlns:p="http://www.springframework.org/schema/p"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    	<bean id="mocksControl" class="foo.MocksControl" />
    
    	<bean id="jdbcOperations" factory-bean="mocksControl" factory-method="createMock"
    		c:_="org.springframework.jdbc.core.JdbcOperations" />
    
    </beans>
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration
    public class FooTests {
    
    	@Autowired
    	private JdbcOperations jdbcOperations;
    
    
    	@Test(expected = UnsupportedOperationException.class)
    	public void foo() {
    		jdbcOperations.execute("sql statement");
    	}
    
    }
    
    public class MocksControl {
    
    	@SuppressWarnings("unchecked")
    	public <T> T createMock(Class<T> toMock) {
    
    		return (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { toMock }, new InvocationHandler() {
    
    			@Override
    			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    				throw new UnsupportedOperationException("mocked!");
    			}
    		});
    	}
    
    }
    

    Regards,

    Sam

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

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    And here's what I used to unit test this:

    	@Test
    	public void parameterizedInstanceFactoryMethod() {
    		DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    
    		RootBeanDefinition rbd = new RootBeanDefinition(MocksControl.class);
    		bf.registerBeanDefinition("mocksControl", rbd);
    
    		rbd = new RootBeanDefinition();
    		rbd.setFactoryBeanName("mocksControl");
    		rbd.setFactoryMethodName("createMock");
    		rbd.getConstructorArgumentValues().addGenericArgumentValue(Runnable.class);
    
    		bf.registerBeanDefinition("mock", rbd);
    
    		Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
    		assertEquals(1, beans.size());
    	}
    

    Note that the implementation of MocksControl is the same as in the above comment.

    See also: GitHub commit b305f0005b.

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

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    This issue is on hold until feedback has been provided by the reporter.

  5. spring-projects-issues commented on Jun 14, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Dmitry Katsubo commented

    Sam, you're absolutely right. I have to use c: instead of p: and thus this my bug report is a complete mistake.

    However even after this correction I get org.springframework.beans.factory.NoSuchBeanDefinitionException on Spring v3.2.2. Perhaps you are testing on SNAPSHOT?

    I think I know where the problem is... The code flow was OK till this very line:

    if (args[i] instanceof Class) {
    	return (Class<?>) args[i];
    }
    

    and it turns out that args[0] is a String ("org.springframework.transaction.support.TransactionOperations"), not Class<TransactionOperations>. As I understand, type conversion didn't take place.

  6. spring-projects-issues commented on Jun 14, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    I actually ran my tests against 4.0 master, but the code in question hasn't changed since 3.2.2. So there (theoretically) shouldn't be any difference.

    What happens if you run the above parameterizedInstanceFactoryMethod() test method against 3.2.2 on your machine?

  7. spring-projects-issues commented on Jun 14, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Dmitry Katsubo commented

    parameterizedInstanceFactoryMethod() works just fine. Yes, because you do addGenericArgumentValue(Runnable.class) – conversion to class is already done.

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

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    Which version of EasyMock are you using?

    From EasyMock 2.3, I see the following declaration:

    public interface IMocksControl extends IExpectationSetters {
        /**
         * Creates a mock object that implements the given interface.
         * @param <T> the interface that the mock object should implement.
         * @param toMock the class of the interface that the mock object should implement.
         * @return the mock object.
         */
        <T> T createMock(Class<T> toMock);
    
        /**
         * Creates a mock object that implements the given interface.
         * @param name the name of the mock object .
         * @param toMock the class of the interface that the mock object should implement.
         * @param <T> the interface that the mock object should implement.
         * @return the mock object.
         * @throws IllegalArgumentException if the name is not a valid Java identifier.
         */
        <T> T createMock(String name, Class<T> toMock);
    

    So the createMock method that Spring uses as the factory method should be the first one that takes a single Class as an argument. If that is not the case, then that's a different issue.

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

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    Dmitry,

    Since I haven't been able to reproduce your problem, could you please create an executable project demonstrating the issue your experiencing?

    Details can be found here: https://github.com/SpringSource/spring-framework-issues#readme

    Cheers,

    Sam

  10. spring-projects-issues commented on Jun 17, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Dmitry Katsubo commented

    Sam, thanks for your comments. In general you're right: #14127 works fine in Spring v3.2.3. It took me some time to find out what is the root of problem and I was on the wrong way to find a problem in GenericTypeResolver. Finally it turned out that <context:component-scan> does not behave correctly with this feature. Namely:

    • if <context:component-scan> takes place after declaration of mocked beans, it works fine
    • if <context:component-scan> takes place before declaration of mocked beans, then autowiring fails for scanned component.
      I would expect that autowiring works in both cases the same way, however I might have wrong expectations.

    The attached project demonstrates the problem. Check the difference between context_scanning.xml and context_scanning_failed.xml.

  11. spring-projects-issues commented on Jun 19, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    Dmitry,

    Thanks so much for providing the passing and failing test cases!

    That helped me investigate the issue more thoroughly, and it turns out that the issue doesn't have to do with component scanning but rather with autowiring in general. Specifically, return type prediction for generic factory methods does not work if type conversion of the method arguments is necessary.

    So, when you said...

    and it turns out that args[0] is a String ("org.springframework.transaction.support.TransactionOperations"), not Class<TransactionOperations>. As I understand, type conversion didn't take place.

    ... I believe you hit the nail on the head.

    With the current code base, the arguments presented to GenericTypeResolver.resolveReturnTypeForGenericMethod() are the raw metadata provided via the bean definition in XML. Thus, the fully qualified class name is in fact a String instead of an instance of Class.

    Note, however, that the correct factory method does in fact get resolved later in ConstructorResolver.instantiateUsingFactoryMethod(), and that's where the type conversion from String to Class occurs.

    So we'll look into options for making the type prediction sync up with the actual factory method resolution.

    Regards,

    Sam

  12. spring-projects-issues commented on Jun 19, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Dmitry Katsubo commented

    Sam, thanks for looking into the issue. Now when issue is narrowed, I think description and title should be updated (e.g. copy-paste context & Java blocks from project I've attached). It is related to #14127 but not directly. Perhaps you can now re-formulate the issue title far better then me, as I still have no clue where is the root of the problem.

  13. spring-projects-issues commented on Sep 30, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    Changed title and issue type to reflect that this is a bug.

  14. spring-projects-issues commented on Oct 14, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Juergen Hoeller commented

    I've fixed this for 4.0 RC1 and 3.2.5 now, consistently resolving class names (which turns out to be the only thing necessary) and moving the entire algorithm from GenericTypeResolver to the internal AutowireUtils helper.

    Juergen

  15. spring-projects-issues commented on Oct 15, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    Thanks, Juergen! :)

  16. added
    type: bug
    in: core
    on Jan 11, 2019
  17. added this to the 3.2.5 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: coretype: bug

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions