aop注解
@Component 加入自定義通知類
@Service 加入服務(wù)層
@Aspect 聲明切面,修飾切面類,獲得通知.配合Component使用
注解開發(fā)通知
定義切入點(diǎn)
@PointCut ,修飾空方法 private void xxx(){} , 之后通過“方法名”獲得切入點(diǎn)引用
在方法前加入注解通知類型:
@Before 前置 加入自定義方法前
@AfterReturning 后置(value="myPoint()",returning="res")
@Around 環(huán)繞
開發(fā)流程
第一步:開發(fā)注解的通知類 如下所示 我注釋了 前置通知以及后置通知笔咽,根據(jù)自己的實(shí)際情況進(jìn)行修改。
@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("這是環(huán)繞的前置");
proceed = proceedingJoinPoint.proceed();
Log.info("這是環(huán)繞的后置");
} catch (Throwable throwable) {
}
return proceed;
}
}
第二步:開發(fā)目標(biāo)接口和實(shí)現(xiàn)類(注解方式)
@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>
第四步: 測(cè)試
一次只開一種通知做測(cè)試颁井,其他的通知先注釋
@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();
}
打印輸出結(jié)果如下所示:
其他情況就不演示了斯议。