gpt4 book ai didi

java - CustomRepositoryImpl 中的 Autowiring bean 为 null

转载 作者:行者123 更新时间:2023-12-02 07:05:38 25 4
gpt4 key购买 nike

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

bean 在 root-context.xml 中声明如下

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

当然是使用正确的命名空间。然后,我尝试使用 @Autowired 将此 bean 注入(inject) 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 发生在 Controller 中。那么为什么 StudyRepositoryImpl 中的 QueryTemplateFactory 为 null,但 @Controller 中的 QueryTemplateFactory 却不然,我该如何解决这个问题?

完整代码可在 GitHub 上获取 https://github.com/joelkuiper/trialverse/tree/feature/injectQueryTemplate

提前致谢!

最佳答案

您可能只需要添加:

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

或者

<context:annotation-config/>

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

关于java - CustomRepositoryImpl 中的 Autowiring bean 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16145722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com