受 spring data awesomeness 的启发,我想创建一个抽象的 RESTController,我可以为我的很多控制器扩展它。我创建了以下类:
@Controller
public abstract class RESTController<E, PK extends Serializable, R extends PagingAndSortingRepository<E, PK>>
{
@Autowired
private R repository;
@RequestMapping(method=RequestMethod.GET, params={"id"})
@ResponseBody
public E getEntity(@RequestParam PK id)
{
return repository.findOne(id);
}
...
}
我希望泛型允许我在存储库中使用@Autowired,但我收到以下错误:
SEVERE: Allocate exception for servlet appServlet
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [org.springframework.data.repository.PagingAndSortingRepository] is defined: expected single matching bean but found 3: [groupRepository, externalCourseRepository, managedCourseRepository]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:800)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
我明白错误告诉我什么,@Autowired 有不止一个匹配项。我很困惑,因为我认为通过创建以下控制器它会起作用:
@Controller
@RequestMapping(value="/managedCourse")
public class ManagedCourseController extends RESTController<ManagedCourse, Long, ManagedCourseRepository>
{
...
}
这很容易通过在 RESTController 中使用这样的方法来解决:
protected abstract R getRepository();
然后在您的实现类中执行此操作:
@Autowired
private ManagedCourseRepository repository;
@Override
protected ManagedCourseRepository getRepository()
{
return repository;
}
我只是想知道是否有人对我如何使它起作用有任何想法。
我还发现了这篇有趣的文章。