Spring 3 DI using generic DAO interface

Posted by Peders on Stack Overflow See other posts from Stack Overflow or by Peders
Published on 2010-05-17T06:52:26Z Indexed on 2010/05/17 7:00 UTC
Read the original article Hit count: 698

I'm trying to use @Autowired annotation with my generic Dao interface like this:

public interface DaoContainer<E extends DomainObject> {
    public int numberOfItems();
    // Other methods omitted for brevity 
}

I use this interface in my Controller in following fashion:

@Configurable
public class HelloWorld {
    @Autowired
    private DaoContainer<Notification> notificationContainer;

    @Autowired
    private DaoContainer<User> userContainer;

    // Implementation omitted for brevity
}

I've configured my application context with following configuration

<context:spring-configured />
<context:component-scan base-package="com.organization.sample">
<context:exclude-filter expression="org.springframework.stereotype.Controller"
   type="annotation" />
</context:component-scan>
<tx:annotation-driven />

This works only partially, since Spring creates and injects only one instance of my DaoContainer, namely DaoContainer. In other words, if I ask userContainer.numberOfItems(); I get the number of notificationContainer.numberOfItems()

I've tried to use strongly typed interfaces to mark the correct implementation like this:

public interface NotificationContainer extends DaoContainer<Notification> { }
public interface UserContainer extends DaoContainer<User> { }

And then used these interfaces like this:

@Configurable
public class HelloWorld {
    @Autowired
    private NotificationContainer notificationContainer;
    @Autowired
    private UserContainer userContainer;
    // Implementation omitted...
}

Sadly this fails to BeanCreationException:

org.springframework.beans.factory.BeanCreationException: Could not autowire field:   private com.organization.sample.dao.NotificationContainer com.organization.sample.HelloWorld.notificationContainer; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.organization.sample.NotificationContainer] 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)}

Now, I'm a little confused how should I proceed or is using multiple Dao's even possible. Any help would be greatly appreciated :)

© Stack Overflow or respective owner

Related posts about spring

Related posts about dependency-injection