aop注解
@Component 加入自定义通知类
@Service 加入服务层
@Aspect 声明切面,修饰切面类,获得通知.配合Component使用
注解开发通知
定义切入点
@PointCut ,修饰空方法 private void xxx(){} , 之后通过“方法名”获得切入点引用
在方法前加入注解通知类型:
@Before 前置 加入自定义方法前
@AfterReturning 后置(value="myPoint()",returning="res")
image.png
@Around 环绕
image.png
开发流程
第一步:开发注解的通知类 如下所示 我注释了 前置通知以及后置通知,根据自己的实际情况进行修改。
@Component("AnnotationSLogAdvice")
@Aspect
public class AnnotationSLogAdvice {
@Pointcut("execution( * com.zyh.service...(..))")
public void myPoint(){
}
/* @Before("myPoint()")
public void myBefore(JoinPoint joinPoint){
Log.info("前置");
}/
/ @AfterReturning(value = "myPoint()" ,returning = "res" )
public void myAfter(JoinPoint joinPoint, Object res){
Log.info("后置");
Log.info("我是返回值:"+res);
}*/
@Around("myPoint()")
public Object myAround(ProceedingJoinPoint proceedingJoinPoint){
Object proceed = null;
try {
Log.info("这是环绕的前置");
proceed = proceedingJoinPoint.proceed();
Log.info("这是环绕的后置");
} catch (Throwable throwable) {
}
return proceed;
}
}
第二步:开发目标接口和实现类(注解方式)
@Service("AnnotationServiceImpl")
public class AnnotationServiceImpl implements AnnotationService {
@Qualifier("AnnotationDaoImpl")
@Autowired
private AnnotationDaoImpl annotationDao;
@Override
public void add() {
annotationDao.addAnnotation();
}
@Override
public String returnAnnotation() {
return annotationDao.returnAnnotation();
}
}
第三步:开启注解扫描,开启Aspect
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.zyh.dao,com.zyh.service,com.zyh.advice"></context:component-scan>
<!-- 2,开启Aspect注解 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
第四步: 测试
一次只开一种通知做测试,其他的通知先注释
@Test
public void testAnnotationBefore(){
ClassPathXmlApplicationContext classPathXmlApplicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
AnnotationService annotationService = (AnnotationService) classPathXmlApplicationContext.getBean("AnnotationServiceImpl");
annotationService.add();
}
@Test
public void testAnnotationAfter(){
ClassPathXmlApplicationContext classPathXmlApplicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
AnnotationService annotationService = (AnnotationService) classPathXmlApplicationContext.getBean("AnnotationServiceImpl");
annotationService.returnAnnotation();
}
@Test
public void testAnnotationAround(){
ClassPathXmlApplicationContext classPathXmlApplicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
AnnotationService annotationService = (AnnotationService) classPathXmlApplicationContext.getBean("AnnotationServiceImpl");
annotationService.add();
}
打印输出结果如下所示:
image.png
其他情况就不演示了。
网友评论