对于基于接口动态代理的 AOP 事务增强来说,由于接口的方法都必然是 public 的,这就要求实现类的实现方法也必须是 public 的(不能是 protected、private 等),同时不能使用 static 的修饰符。所以,可以实施接口动态代理的方法只能是使用 public 或 public final 修饰符的方法,其他方法不可能被动态代理,相应的也就不能实施 AOP 增强,换句话说,即不能进行 Spring 事务增强了。
@Service("installedRecordService")
public class InstalledRecordServiceImpl implements InstalledRecordService {
@Resource
private InstalledRecordMapper installedRecordMapper;
@Override
public void getInstalledApks() {
List<String> imeiSnCodes = installedRecordMapper.queryImeiCode();
if (imeiSnCodes != null && imeiSnCodes.size()> 0) {
for(int i=0;i<imeiSnCodes.size();i++){
//获取当前代理对象,进行调用
((InstalledRecordService) AopContext.currentProxy()).getInstalledApk(imeiSnCodes.get(i));
}
}
}
}
public abstract class AopContext {
private static final ThreadLocal<Object> currentProxy = new NamedThreadLocal<Object>("Current AOP proxy");
public static Object currentProxy() throws IllegalStateException {
Object proxy = currentProxy.get();
if (proxy == null) {
throw new IllegalStateException(
"Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.");
}
return proxy;
}
static Object setCurrentProxy(Object proxy) {
Object old = currentProxy.get();
if (proxy != null) {
currentProxy.set(proxy);
}
else {
currentProxy.remove();
}
return old;
}
}
@Service("installedRecordService")
public class InstalledRecordServiceImpl implements InstalledRecordService{
//注入自身
@Resource
private InstalledRecordService installedRecordService;
@Resource
private InstalledRecordMapper installedRecordMapper;
@Override
public void getInstalledApks() {
List<String> imeiSnCodes = installedRecordMapper.queryImeiCode();
if (imeiSnCodes != null && imeiSnCodes.size()> 0) {
for(int i=0;i<imeiSnCodes.size();i++){
installedRecordService.getInstalledApk(imeiSnCodes.get(i));
}
}
}