
项目的包:

pom依赖导入有关aop的包:
org.aspectj aspectjweaver 1.9.4
代理类交给spring来实现。
UserService:
package com.Li.service;public interface UserService {public void add();public void delete();public void update();public void select();
}
UserServiceImpl:
package com.Li.service;public class UserServiceImpl implements UserService{@Overridepublic void add() {System.out.println("增加了一个用户!");}@Overridepublic void delete() {System.out.println("删除了一个用户!");}@Overridepublic void update() {System.out.println("修改了一个用户!");}@Overridepublic void select() {System.out.println("查询了一个用户!");}
}
log:
package com.Li.log;import org.springframework.aop.MethodBeforeAdvice;import java.lang.reflect.Method;
//前置日志
public class log implements MethodBeforeAdvice {//method: 要执行的目标对象的方法//args:参数//target:目标对象@Overridepublic void before(Method method, Object[] args, Object target) throws Throwable {System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");}
}
AfterLog:
package com.Li.log;import org.springframework.aop.AfterReturningAdvice;import java.lang.reflect.Method;
//后置日志
public class AfterLog implements AfterReturningAdvice {//returnValue: 返回值.由于是AfterReturning,所以有返回值@Overridepublic void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);}
}
方式一:(使用spring的接口实现动态代理类)
applicationContext.xml:
MyTest:(测试)(不变)
import com.Li.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class MyTest {public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");//动态代理代理的是接口:注意点UserService userService = context.getBean("userService", UserService.class);userService.add();}
}

增加一个类:

DiyPointCut:
package com.Li.diy;public class DiyPointCut {public void before(){System.out.println("=====方法执行前=====");}public void after(){System.out.println("=====方法执行后=====");}}
applicationContext.xml:(看方式二)
测试(代码不变直接测试):

AnnotationPointCut:
package com.Li.diy;//方式三:使用注解方式实现AOPimport org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;@Aspect//标记这个类是一个切面
public class AnnotationPointCut {@Before("execution(* com.Li.service.UserServiceImpl.*(..))")public void before(){System.out.println("=====方法执行前=====");}@After("execution(* com.Li.service.UserServiceImpl.*(..))")public void after(){System.out.println("=====方法执行后=====");}}
applicationContext.xml:
直接测试

三种方式都可以实现AOP。第一种全面,第二种便于理解,第三种方便。你可以自己选择自己喜欢的方式。
下一篇:以下关于条件语句的说法正确的是