2013-02-28 94 views
1

我试图在数据库应用程序中进行“按类型查找”研究。 特别是,我有一个类型的层次结构:母亲< - Child1,Child2。 我有3个相应的存储库,即类注释@Repository和扩展PagingAndSortingRepository。使用反射来查找实例化Spring Data Repository的类的对象

现在,我有一个控制器需要加载数据库中的所有类型Child1(或Child2)的实例。

这是我在类ControllerClassForTheSearch方法建议:

public List<? extends Mother> findMotherByType(Class classToSearch) 
     throws FindException { 

    PagingAndSortingRepository<? extends Mother, Long> repo; 
    try { 
     repo = beanFactory.createBean(classToSearch); 
    } catch (Exception e) { 
     throw new FindException (this 
       .getClass().getName(), classRepository); 
    } 

    return repo.findAll(); 
} 

BeanFactory的变量定义为跟随在同一类:

@Controller 
public class ControllerClassForTheSearch implements BeanFactoryAware { 
    private AutowireCapableBeanFactory beanFactory; 

    @Override 
    public void setBeanFactory(final BeanFactory beanFactory) 
     throws BeansException { 
     this.beanFactory = (AutowireCapableBeanFactory) beanFactory; 
    } 
    [...] // rest of the class code 

但是,这是行不通的:我的存储库是接口,所以它们不能被创建(这是我得到的错误)。 在其他类中,存储库是自动装配的变量,它们工作正常,包括Mother,Child1和Child2的变量。

你有什么想法可以找到我找到类型为Child1的类的结果吗?

回答

0

我用getBean替换了createBean,它工作。

1

您可能想看看Spring Data Commons中的Repositories辅助类。您可以从ListableBeanFactory创建一个,然后通过受管域类型访问存储库。

相关问题