一、问题背景:
是由于new thread不在spring容器中,所以无法获得spring中的bean对象。也会遇到事务丢失,抛出异常javax.persistence.TransactionRequiredException: no transaction is in progress,等情况。
二、解决方案:
1.在@Transactional(readOnly = true) 可以解决no transaction is in progress。
2.以下方式可以解决无法获取bean和事务丢失问题:
@Component
public class BeanContext implements ApplicationContextAware {
// Spring应用上下文环境
private static ApplicationContext applicationContext;
/*
* 实现了ApplicationContextAware 接口,必须实现该方法;
* 通过传递applicationContext参数初始化成员变量applicationContext
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BeanContext.applicationContext = applicationContext;
}
public static ApplicationContext getA