从静态上下文调用 @Autowired Repository

Call a @Autowired Repository from a static context

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

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

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

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

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

的某些阶段注入

您应该将包含 createEntity 方法的 class 声明为 Spring bean(例如 @Component)。然后你可以在所有其他需要调用 createEntity.

的 classes 中注入这个 bean(使用 @Autowired

我不推荐这个,但是由于任何原因如果你不能改变原来的 class (到一个单例),你可以考虑下面的方法,它调用里面的 createEntity(entityManager) @PostConstruct 方法:

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);
    }

}