简体   繁体   中英

autowire Spring repository into generic field (Spring 4, Hibernate 4)

I am trying to build extensible application, that uses lot of generics. So far I have code:

@Component
@Named
@Scope("session")
@Repository
public interface FrameworkRepository<E extends FrameworkEntity> 
    extends PagingAndSortingRepository<E, Long> {
}

@Component
@Named
@Scope("session")
@Repository
public interface OrderRepository extends FrameworkRepository<Order> {
}

@Component
@Named 
@Scope("session")
public class FrameworkService<R extends FrameworkRepository> implements Serializable {
    @Autowired
    private R repository;
}

@Component
@Named
@Scope("session")
public class OrderService extends FrameworkService<OrderRepository> {
    public OrderService() { 
    }
}

However, when I am trying to use OrderService instance in facelets page, there is exception with the message:

nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [...FrameworkRepository] 
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)}

I guess, that the root problem can be my use of generics. Maybe Spring Data (repositories) can not automaticall create class from the OrderRepository interface, or maybe Spring @Autowired can not find the instance (created by Spring Data on the fly) of OrderRepository and autowire it into generic field.

I know that in any time I can find workarounds without use of generics, but that involves much unnecesary code. Generics can lead to more concise code.

I use Hibernate 4.x, Spring 4.x, JPA 2.1.

I had to add

<jpa:repositories base-package="dk.nmc.imarket.data"
    entity-manager-factory-ref="entityManagerFactory">
</jpa:repositories>

in my applicationContext.xml and I remode unnecesary annotations from the repositories - they are just repositories and not the full Spring beans by name and for session. It helped so far.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM