Spring Dependency Injection入JPA实体监听器

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

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

@Component public final class BeanUtil { private static ApplicationContext context; private BeanUtil(ApplicationContext context) { BeanUtil.context = context; } public static  T getBean(Class clazz) throws BeansException { Assert.state(context != null, "Spring context in the BeanUtil is not been initialized yet!"); return context.getBean(clazz); } } 

你可以尝试这个解决方案

 import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public final class AutowireHelper implements ApplicationContextAware { private static final AutowireHelper INSTANCE = new AutowireHelper(); private static ApplicationContext applicationContext; private AutowireHelper() { } /** * Tries to autowire the specified instance of the class if one of the specified beans which need to be autowired * are null. * * @param classToAutowire the instance of the class which holds @Autowire annotations * @param beansToAutowireInClass the beans which have the @Autowire annotation in the specified {#classToAutowire} */ public static void autowire(Object classToAutowire, Object... beansToAutowireInClass) { for (Object bean : beansToAutowireInClass) { if (bean == null) { applicationContext.getAutowireCapableBeanFactory().autowireBean(classToAutowire); return; } } } /** * @return the singleton instance. */ public static AutowireHelper getInstance() { return INSTANCE; } @Override public void setApplicationContext(final ApplicationContext applicationContext) { AutowireHelper.applicationContext = applicationContext; } 

}

接着

  @Autowired SomeService thatToAutowire; AutowireHelper.autowire(this, this.thatToAutowire);//this in the method