将 Spring 依赖注入到 JPA 实体侦听器中 [英] Spring Dependency Injection into JPA entity listener

查看:28
本文介绍了将 Spring 依赖注入到 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 依赖注入到 JPA 实体侦听器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆