Spring中AOP實例詳解
需要增強的服務
假如有以下service,他的功能很簡單,打印輸入的參數並返回參數。
@Service
public class SimpleService {
public String getName(String name) {
System.out.println(get name is: + name);
return name;
}
}
定義切面和切點
@Component
@Aspect
public class L
ogAspect {
// 定義切點
@Pointcut(within(com.ydoing.service..*))
// @Pointcut(execution(* com.ydoing.service.*.*(..)))
public void pointCut() {
}
}
Before增強處理
// 定義Before增強處理
// 在目標方法調用之前執行增強處理
@Before(pointCut())
public void before(JoinPoint jp) {
// 獲取連接點傳入參數
// Object args = jp.getArgs();
System.out.println(Before增強處理--execute before target method call);
}
--------------------------------------------------------------------------------
測試輸出:
Before增強處理--execute before target method call
get name is: Bob
AfterReturning增強
// 在目標方法調用之後執行增強處理
@AfterReturning(pointcut = pointCut(), returning = ret)
public void afterReturning(JoinPoint jp, Object ret) {
System.out.println(AfterReturnin增強處理--execute after target method call, return value is : + ret);
}
--------------------------------------------------------------------------------
測試輸出:
get name is: Bob
AfterReturnin增強處理--execute after target method call, return value is :Bob
Around增強
@Around(pointCut())
public void around(ProceedingJoinPoint jp) {
System.out.println(Around增強--around start...);
Object[] args = jp.getArgs();
// 修改目標方法傳入的參數
args[0] = around_add_ + args[0];
try {
System.out.println(修改傳入參數後執行輸出:);
jp.proceed(args);
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Around增強--around end);
}
--------------------------------------------------------------------------------
輸出:
Around增強--around start...
修改傳入參數後執行輸出:
get name is: around_add_Bob
Around增強--around end
After增強
// 無論是否發生異常都會 處理
@After(pointCut())
public void after() {
System.out.println(After增強--always do no matter what happen);
}
--------------------------------------------------------------------------------
輸出:
get name is: Bob
After增強--always do no matter what happen
AfterThrowing增強
@AfterThrowing(pointcut = pointCut(), throwing = ex)
public void afterThrowing(JoinPoint jp, Throwable ex) {
System.out.println(error is: + ex);
}
這裡沒拋異常,就沒有輸出了
測試代碼如下
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = com.ydoing.service,com.ydoing.aspect)
public class AppConfig {
public static void main(String[] args) {
@SuppressWarnings(resource)
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
SimpleService service = ctx.getBean(SimpleService.class);
service.getName(Bob);
}
}
Spring AOP進行日志記錄 http://www.linuxidc.com/Linux/2015-11/124731.htm
使用Spring AOP進行性能監控 http://www.linuxidc.com/Linux/2012-07/64681.htm
利用Spring AOP 更新Memcached 緩存策略的實現 http://www.linuxidc.com/Linux/2012-03/56503.htm
Spring AOP的兩種代理 http://www.linuxidc.com/Linux/2015-11/125017.htm
Spring AOP的注解實例 http://www.linuxidc.com/Linux/2015-11/125018.htm