0

我刚开始使用Spring Data,我正在尝试向我的存储库添加一个自定义方法,这需要另一个 bean(最好只创建一次(即单例))

bean 像这样在 root-context.xml 中声明

<bean class="org...CachedQueryTemplateFactory" /> 

当然,使用适当的命名空间。然后我尝试使用 @Autowired 将此 bean 注入到 CustomRepositoryImpl

@Getter
@Setter
@Component
public class StudyRepositoryImpl implements StudyRepositoryCustom {
    @PersistenceContext private EntityManager d_em;
    @Autowired private QueryTemplateFactory queryTemplateFactory;

    @Override
    public List<Study> findStudies(
            UUID indication,
            List<UUID> variables,
            List<UUID> treatments) {
        QueryTemplate template = this.queryTemplateFactory.buildQueryTemplate("...");
        ...
    }
}

但是,在运行代码时,我得到 NullPointerException。在 @Controller 中进行接线然后将引用传递给存储库时,它可以工作,但我不希望 DI 发生在控制器中。那么,为什么 StudyRepositoryImpl 中的 QueryTemplateFactory 为空,而 @Controller 中却没有,我该如何解决这个问题?

GitHub https://github.com/joelkuiper/trialverse/tree/feature/injectQueryTemplate上提供了完整代码

提前致谢!

4

1 回答 1

2

您可能只需要添加:

<context:component-scan base-package="packagewithservices"/>

或者

<context:annotation-config/>

其中任何一个都注册了一个AutowiredAnnotationBeanPostProcessor负责在@Autowired字段中进行布线。我链接到的 javadoc 有更多详细信息。

于 2013-04-22T14:07:16.417 回答