Skip to content

@Autowire does not work as expected for Collections based Repository implementation [SPR-3946] #8626

Closed

Description

@spring-projects-issues

Chris Beams opened SPR-3946 and commented

Consider the following Repository artifacts:

public interface PersonRepository extends Set<Person> {} 

final class JdoPersonRepository extends AbstractSet<Person> implements PersonRepository {
    // ... implementation omitted
}

And the test that excercises them:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class PersonRepositoryTests {
    @Autowired
    private PersonRepository personRepository;

        // test methods omitted...
}

}

And finally, the named-by-convention beans XML used by the test (PersonRepositoryTests-context.xml):

<beans ...>
    <bean id="pmf" class="org.springframework.orm.jdo.LocalPersistenceManagerFactoryBean">
        <property name="configLocation" value="classpath:jpox.properties"/>
    </bean>

    <bean id="pmfProxy" class="org.springframework.orm.jdo.TransactionAwarePersistenceManagerFactoryProxy">
        <property name="targetPersistenceManagerFactory" ref="pmf" />
        <property name="allowCreate" value="false" />
    </bean>

    <bean id="personRepository" class="com.foo.domain.JdoPersonRepository">
        <constructor-arg ref="pmfProxy"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jdo.JdoTransactionManager">
        <property name="persistenceManagerFactory" ref="pmf"/>
    </bean>

    <tx:annotation-driven/>
</beans>

Expected behavior when running the test:

  1. Spring bootstraps an ApplicationContext backed by PersonRepositoryTests-context.xml
  2. The @Autowired 'personRepository' dependency is detected within my PersonRepositoryTests class
  3. Spring looks up this resource by type and injects it directly at the field level, with no further ado.

Actual behavior when running the test:

Steps (1) and (2) execute as expected.

Step (3) however, gets more complicated. Because java.util.Collection is assignable from PersonRepository, the logic in AbstractAutowireCapableBeanFactory (fisheye: http://tinyurl.com/2utx6u) assumes that I want my JdoPersonRepository bean to be autowired with beans of its generic collection parameter type (which is Person in this case). Furthermore it fails upon being unable to locate at least one such Person beans in the container. Relevant excepts from the resulting stack trace follow:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.foo.MyTests': Autowiring of fields failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.foo.domain.PersonRepository com.foo.MyTests.personRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.foo.domain.Person] is defined: Unsatisfied dependency of type [com.foo.domain.Person]: expected at least 1 matching bean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:208)
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.foo.domain.Person] is defined: Unsatisfied dependency of type [com.foo.domain.Person]: expected at least 1 matching bean
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveDependency(AbstractAutowireCapableBeanFactory.java:373)

Suffice to say this behavior is not what I want or expect to happen.

But, as the issue type of 'Improvement' suggests, I don't know that I can call this a 'bug' either. I can see that the original design intent is being fulfilled; it's just that I have a use case for which that design causes problems.

Could we conceive a way to (configurably) relax this assumption that Collection-based beans must have one or more element beans declared in the container?

Also note, this issue is somewhat related to #8349, where I encountered a similar problem with the container attempting to call size() on beans assignable to Collection. Juergen relaxed this behavior, and I'm hoping we can do the same here. (see especially his comment on the issue: http://opensource.atlassian.com/projects/spring/browse/SPR-3668#action_24701)

I do have a workaround in the meantime: instead of declaring my dependency by interface:

@Autowired
private PersonRepository personRepository; 

I'm now declaring by concrete type:

@Autowired
private JdoPersonRepository personRepository; 

This bypasses the '&& type.isInterface()' condition (see fisheye link above), and allows the bean to simply be returned and injected without further complication.

At any rate, thanks for looking into this.

  • Chris Beams

Affects: 2.1 M4

Issue Links:

Activity

  1. spring-projects-issues commented on Sep 29, 2007

    @spring-projects-issues
    CollaboratorAuthor

    Chris Beams commented

    The fisheye link above was not to the exact line as I had intended (line 362). Here's a better link: http://tinyurl.com/2w77zv

    The formatting on the test case was a bit off, too. Here's a better look at it:

    @RunWith(SpringJUnit4ClassRunner.class) 
    @ContextConfiguration 
    public class PersonRepositoryTests { 
        @Autowired 
        private PersonRepository personRepository; 
    
            // test methods omitted... 
    } 
    
  2. spring-projects-issues commented on Sep 30, 2007

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    Hi Chris,

    I do have a workaround in the meantime: instead of declaring my dependency by interface:

    @Autowired
    private PersonRepository personRepository;
    

    I'm now declaring by concrete type:

    @Autowired
    private JdoPersonRepository personRepository;
    

    There is actually a much simpler solution. Whenever @Autowired semantics do not meet
    your needs, you always have to option of injecting dependencies "by name" using the
    @Resource annotation from JSR 250.

    Try the following instead of your aforementioned work-around:

    @Resource
    private PersonRepository personRepository;
    

    This is 100% in line with @Resource semantics in a Spring container and is therefore
    not even a "work-around". ;)

    cheers,

    Sam

  3. spring-projects-issues commented on Sep 30, 2007

    @spring-projects-issues
    CollaboratorAuthor

    Chris Beams commented

    Good call. I thought of this originally, but didn't want to hassle with a dependency on javaee-api just for the @Resource annotation (I'm using JDK5). It's clearly worth the hassle at this point :-)

    I've swapped out the usage of @Autowired with @Resource, and everything 'just works'. Thanks.

  4. spring-projects-issues commented on Sep 30, 2007

    @spring-projects-issues
    CollaboratorAuthor

    Sam Brannen commented

    Good call. I thought of this originally, but didn't want to hassle with a
    dependency on javaee-api just for the @Resource annotation (I'm using JDK5).

    Well, the "Common Annotations for Java" from JSR 250 are actually part of JSE 6.
    So from JDK 1.6 onwards, you don't even need to do anything special to use these
    annotations. JSR 250 annotations are of course also bundled with JEE 5.

    For JSE 5, however, you only need to include the jsr250-api-1.0.jar (which
    is just 6 KB) in your projects. If you're using Maven2, you can include the
    following dependency in your POM:

    <dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>jsr250-api</artifactId>
    <version>1.0</version>
    </dependency>

    So in that regard, I consider this a very small dependency for JSE 5, and once
    your projects migrate to Java 6, you'll get these annotations out-of-the-box.

    I've swapped out the usage of @Autowired with @Resource, and everything
    'just works'. Thanks.

    Great!

    Glad to be of service,

    Sam

  5. spring-projects-issues commented on Sep 30, 2007

    @spring-projects-issues
    CollaboratorAuthor

    Chris Beams commented

    For JSE 5, however, you only need to include the jsr250-api-1.0.jar

    Perfect. Thanks for pointing that out.

  6. spring-projects-issues commented on Jul 7, 2011

    @spring-projects-issues
    CollaboratorAuthor

    Chris Beams commented

    Please see #13164, which aims to address this and a number of other similar issues related to collection autowiring.

  7. added
    type: enhancement
    in: core
    status: duplicate
    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: corestatus: duplicatetype: enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions