背景:课本上是注解和Xml文件混用的方式,研究了一下用配置类加注解和测试方法实现各种通知方式的切入。
1.首先dao的接口,增删改查
public interface UserDaoAspect {public void add();public void delete();public void update();public void select();
}
2.dao的实现类
@Repository("UserDaoAspectImpl")
public class UserDaoAspectImpl implements UserDaoAspect{@Overridepublic void add() {System.out.println("添加用户");}@Overridepublic void delete() {System.out.println("删除用户");//int flag = 1/0;}@Overridepublic void update() {System.out.println("更新用户");}@Overridepublic void select() {System.out.println("查询用户");}
}
3.切入面和切入点
@Component
@Aspect
public class AnnotationAdvice {@Pointcut("execution(* com.awei.aop.dao.UserDaoAspectImpl.*(..))")public void pointcut(){}//前置通知@Before("pointcut()")public void before(JoinPoint joinPoint){System.out.println("执行前置通知");System.out.println("目标类:"+joinPoint.getTarget());System.out.println("目标类的调用方法"+joinPoint.getSignature().getName());}//返回通知@AfterReturning("pointcut()")public void afterReturningTest(JoinPoint joinPoint){System.out.println("执行了返回通知,且是无异常时的调用");System.out.println("被织入增强处理的目标方法:"+joinPoint.getSignature().getName());}//环绕通知@Around("pointcut()")public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {System.out.println("执行了环绕通知前---------------------------------");Object proceed = proceedingJoinPoint.proceed();System.out.println("执行了环绕通知后---------------------------------");return proceed;}//异常通知@AfterThrowing("pointcut()")public void afterException(){System.out.println("执行了异常通知");}//后置通知@After("pointcut()")public void after(){System.out.println("执行了后置通知");}
}
4.配置类
@Configuration
@ComponentScan("com.awei.aop") //包扫描
@EnableAspectJAutoProxy //开启自动代理
public class AnnotationConfig {}
5.测试方法
public class AopAnitationTest {@Testpublic void aopxml(){//基于AnnotationConfigApplicationContext创建ioc容器AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AnnotationConfig.class);UserDaoAspect userDaoAspect = (UserDaoAspect) context.getBean("UserDaoAspectImpl");userDaoAspect.add();}}
运行结果: