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
- 如何使用SolrJ获取solr服务器中所有核心的列表
- 如何在订阅模式“两者”中添加名册
- 在捕获“InterruptedException”之后,为什么“Thread.currentThread()。isInterrupted()”的值为false?
- 使用ScriptEngine从JavaScript调用Java方法
- 为什么Mockito @InjectMocks可能是一个避免的事情?
- 使用SWIG和C ++的std :: map时没有Java的迭代器
- 带变量的Servlet映射(Tomcat 7.0)
- 如何让Swig正确地将在C中修改的char *缓冲区包装为Java Something-other?
- 在PHP中使用RSA的MD5