Spring Dependency Injection into JPA entity listener

前端 未结 3 717
礼貌的吻别
礼貌的吻别 2020-12-10 09:33

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

3条回答
  •  攒了一身酷
    2020-12-10 10:15

    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 getBean(Class clazz) throws BeansException {
    
            Assert.state(context != null, "Spring context in the BeanUtil is not been initialized yet!");
            return context.getBean(clazz);
        }
    }
    

提交回复
热议问题