本文介绍了Spring Dependency Injection入JPA实体监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个Spring依赖注入到JPA实体监听器中。我知道我可以使用@Configurable和Spring的AspectJ weaver作为javaagent解决这个问题,但这似乎是一个hacky解决方案。有没有其他方法可以完成我想要做的事情?

I need to have a Spring dependency injected into a JPA entity listener. I know I can solve this using @Configurable and Spring's AspectJ weaver as javaagent, but this seems like a hacky solution. Is there any other way to accomplish what I'm trying to do?

推荐答案

另一个技巧是使用静态实现一个实用程序类帮助您在任何地方使用Spring bean的方法,不仅仅是在托管类中:

Another trick is to implement an utility class with static method that helps you to use Spring beans everywhere, not only in managed classes:

@Component
public final class BeanUtil {

    private static ApplicationContext context;

    private BeanUtil(ApplicationContext context) {
        BeanUtil.context = context;
    }

    public static <T> T getBean(Class<T> clazz) throws BeansException {

        Assert.state(context != null, "Spring context in the BeanUtil is not been initialized yet!");
        return context.getBean(clazz);
    }
}

这篇关于Spring Dependency Injection入JPA实体监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 03:03