将 Spring 依赖注入到 JPA 实体侦听器中

2022-01-18 00:00:00 spring java jpa spring-data spring-data-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);
    }
}

相关文章