spring aop 003: 通知
阿新 • • 發佈:2018-12-10
package com.thereisnospon.spring.demo.course.imp.c004_aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
public class T005_Aop_Normal {
public static class BookService {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Aspect
public static class MyAspect {
@Pointcut("execution(* com.thereisnospon.spring.demo.course.imp.c004_aop.T005_Aop_Normal.BookService.getName())")
public void getPointcut() {
//empty..
}
/**
* 繫結引數
*
* @param name
*/
@Pointcut("execution(* com.thereisnospon.spring.demo.course.imp.c004_aop.T005_Aop_Normal.BookService.setName(String)) && args(name)")
public void setPointcut(String name) {
//empty..
}
/**
* 前置
*/
@Before("getPointcut()")
public void beforeGet() {
System.out.println("beforeGet");
}
/**
* 後置
*
* @param name
*/
@After("setPointcut(name)")
public void afterSet(String name) {
System.out.println("afterSet : " + name);
}
/**
* 返回
*
* @param ret
*/
@AfterReturning(pointcut = "getPointcut()", returning = "ret")
public void afterReturn(Object ret) {
System.out.println("afterReturn " + ret);
}
/**
* 異常
*
* @param ex
*/
@AfterThrowing(pointcut = "getPointcut()", throwing = "ex")
public void afterThrow(Throwable ex) {
System.out.println("afterThrow" + ex);
}
/**
* 環繞
*
* @param joinPoint
*/
@Around("getPointcut()")
public void around(ProceedingJoinPoint joinPoint) {
try {
System.out.println("around before");
Object obj = joinPoint.proceed();
System.out.println("around after " + obj);
} catch (Throwable e) {
e.printStackTrace();
System.out.println("processed ex " + e.getMessage());
}
}
}
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
public static class Config {
@Bean
public BookService bookService() {
return new BookService();
}
@Bean
public MyAspect myAspect() {
return new MyAspect();
}
}
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
BookService bookService = (BookService) context.getBean("bookService");
bookService.setName("name");
bookService.getName();
}
}