@Pointcut定義一個切入點spring
1 @Pointcut("execution(public * com.bxw.aop.service.*.*(..))") 2 public void myMethod(){};
這代表定義一個切入點,該切入點名爲myMethodapp
該切入點位置在com.bxw.aop.service中的全部類的全部方法。spa
1 package com.bxw.aop.interceptor; 2 3 import org.aspectj.lang.ProceedingJoinPoint; 4 import org.aspectj.lang.annotation.Around; 5 import org.aspectj.lang.annotation.Aspect; 6 import org.aspectj.lang.annotation.Pointcut; 7 import org.springframework.stereotype.Component; 8 9 @Aspect 10 @Component 11 public class UserServiceInterceptor { 12 @Pointcut("execution(public * com.bxw.aop.service.*.*(..))") 13 public void myMethod(){}; 14 15 @Around("myMethod()") 16 public void aroundMethod(ProceedingJoinPoint pjp){ 17 System.out.println("login start"); 18 try { 19 pjp.proceed(); 20 } catch (Throwable e) { 21 e.printStackTrace(); 22 } 23 System.out.println("login end"); 24 } 25 }
pjp.proceed啓動方法執行。code
==========分界線===================component
配置文件配置:xml
applicationContext.xmlblog
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 3 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc" 4 xmlns:cache="http://www.springframework.org/schema/cache" 5 xsi:schemaLocation=" 6 http://www.springframework.org/schema/context 7 http://www.springframework.org/schema/context/spring-context.xsd 8 http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans.xsd 10 http://www.springframework.org/schema/tx 11 http://www.springframework.org/schema/tx/spring-tx.xsd 12 http://www.springframework.org/schema/jdbc 13 http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd 14 http://www.springframework.org/schema/cache 15 http://www.springframework.org/schema/cache/spring-cache-3.1.xsd 16 http://www.springframework.org/schema/aop 17 http://www.springframework.org/schema/aop/spring-aop.xsd 18 http://www.springframework.org/schema/util 19 http://www.springframework.org/schema/util/spring-util.xsd"> 20 <!-- 初始化bean --> 21 <context:component-scan base-package="com.bxw.aop.*"></context:component-scan> 22 <!-- 初始化aop --> 23 <!-- 將interceptor聲明爲bean --> 24 <bean id="myInterceptor" class="com.bxw.aop.interceptor.UserServiceInterceptor"></bean> 25 <aop:config> 26 <aop:aspect id="myAspect" ref="myInterceptor"> 27 <aop:around method="aroundMethod" pointcut="execution(public * com.bxw.aop.service.*.*(..))"/> 28 </aop:aspect> 29 </aop:config> 30 </beans>