spring aop,静态及动态代理例子
//依赖<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
@Aspect
@Component
public class LogUtil {
@Pointcut("execution(public * com.ygsj.controller.*Controller.add*(..)) || execution(public * com.ygsj.controller.*Controller.update*(..)) || execution(public * com.ygsj.controller.*Controller.del*(..))" )
public void point(){
}
@AfterReturning("point()")
public void afterReturning(JoinPoint joinPoint){
String className = joinPoint.getSignature().getDeclaringTypeName();
String methodName = joinPoint.getSignature().getName();
String str = methodName.substring(0,3);
String content = "类"+className+"方法"+methodName+"的";
String nowTime = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date());
switch (str){
case "add":content += "添加操作";
break;
case "upd":content += "修改操作";
break;
case "del":content += "删除操作";
break;
default:
break;
}
System.out.println(content+"_________"+nowTime);
}
@AfterThrowing("point()")
public void afterThrowing(){
System.out.println("执行失败");
}
@Before("point()")
public void before(){
System.out.println("开始保存日志");
}
@After("point()")
public void after(){
System.out.println("保存日志执行完成");
}
}
静态代理实现:接口实现
public interface JingtaiService { public void save(); public void del(); } public class JingtaiServiceImpl implements JingtaiService { @Override public void save() { System.out.print("保存数据"); } @Override public void del() { System.out.print("删除数据"); } } public class JingtaiProxy implements JingtaiService { @Autowired private JingtaiService target; public JingtaiProxy(JingtaiService target){ this.target = target; } @Override public void save() { System.out.print("开始事物"); target.save(); System.out.print("结束事物"); } @Override public void del() { System.out.print("开始事物"); target.del(); System.out.print("结束事物"); } }
测试:
public static void main(String[] args) { JingtaiService jm = new JingtaiServiceImpl(); JingtaiProxy jp = new JingtaiProxy(jm); jp.save(); }
动态代理:不需要接口实现,jdk方式实现
public class DongtaiProxy { private Object target; public DongtaiProxy(Object target) { this.target = target; } //ClassLoader loader,:指定当前目标对象使用类加载器,获取加载器的方法是固定的 //Class<?>[] interfaces,:目标对象实现的接口的类型,使用泛型方式确认类型 //InvocationHandler h:事件处理,执行目标对象的方法时,会触发事件处理器的方法,会把当前执行目标对象的方法作为参数传入 public Object getProxy(){ return Proxy.newProxyInstance( target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object o, Method method, Object[] objects) throws Throwable { System.out.print("开始动态事物"); Object returnvalue = method.invoke(target,objects); System.out.print("提交事物"); return returnvalue; } } ); } }
测试:
public static void main(String[] args) { JingtaiService jm = new JingtaiServiceImpl(); JingtaiService js = (JingtaiService)new DongtaiProxy(jm).getProxy(); js.save(); js.del(); }