【问题标题】:Call a @Autowired Repository from a static context从静态上下文调用 @Autowired 存储库
【发布时间】:2018-02-08 17:39:14
【问题描述】:

我有一个静态的 createEntity 方法,因为我需要从其他实体调用它,在这个方法中,我需要调用一个存储库,但逻辑上我不能这样做,因为它是非静态的。

public static Client createEntity(EntityManager em) {
   default_operation = operationRepository.save(OperationResource.createEntity(em));
}

我不会问我是否对此感到震惊,我尝试按照其他解决方案的建议使用 @Autowired 构造函数,但这不适用于存储库。

如果有人有想法或解决方法,我将不胜感激!

【问题讨论】:

  • 如果您没有其他选择,您可以从应用程序上下文中获取 bean。初始化时将其保存在静态字段中并从createEntity 访问它(您还需要以某种方式确保它已经初始化)。做 werner 在他的回答中建议的会好得多。

标签: java spring spring-boot jhipster autowired


【解决方案1】:

使用静态方法会导致问题(不仅在 Spring 中)。原因之一是类的自动装配属性在静态上下文中不可用。它们仅在Spring's lifecycle 的某些阶段注入。

您应该将包含createEntity 方法的类声明为Spring bean(例如@Component)。然后你可以在所有其他需要调用createEntity的类中注入这个bean(使用@Autowired)。

【讨论】:

  • 是的,但问题是这个类是一个Test类
  • 你也可以在测试类中使用'@Autowired'。您可能只需要为您的测试提供一个 Spring 配置。也许this answer 有帮助
  • 那么,从一个测试类中,我可以创建一个带有@Autowired 注释的ClientTest 类型的属性吗?
  • 是的,查看示例here。尤其是“JUnitSpringExample”类
【解决方案2】:

我不建议这样做,但由于任何原因,如果您无法更改原始类(为单例),您可以考虑以下方法,它在 @PostConstruct 方法中调用 createEntity(entityManager)

public class MyRepository {

    private EntityManager entityManager;

    private static Client client;

    @Autowired
    public MyRepository(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @PostConstruct
    public void init() {
        //Now call your createEntity(entityManager) method
        client = EntityUtils.createEntity(entityManager);
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 2014-12-25
    • 1970-01-01
    • 2016-10-02
    • 2010-12-02
    • 2017-03-07
    相关资源
    最近更新 更多