获取spring代理对象的两种方式
@Transactional(propagation = Propagation.REQUIRED)
第一种 从spring容器中直接获取代理对象
@Autowired
ApplicationContext applicationContext;
applicationContext.getBean(接口类.class)
第二种 使用spring提供的静态方法获取代理对象
(FridayService) AopContext.currentProxy();
代码示例
@Service
public class FridayServiceImpl implements FridayService{
@Autowired
FridayMapper fridayMapper;
@Autowired
ApplicationContext applicationContext;
@Override
public ArrayList<Employee> getAllEmployees() {
return fridayMapper.getAllEmployees();
}
@Override
public User getUser() {
return fridayMapper.getUser();
}
public void test(){
}
@Transactional
public Integer saveUser(User user) {
FridayService bean = applicationContext.getBean(FridayService.class);
bean.updateUser();
// Object proxy = (FridayService) AopContext.currentProxy();
System.out.println("aopProxy"+ bean);
int num = 1/0;
Integer integer = fridayMapper.saveUser(user);
return integer;
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void updateUser(){
fridayMapper.updateUser();
}
}
经验证updateUser事务是生效的 !!!
转载自:https://juejin.cn/post/6908694078049910798