需要导入包:
<dependency>
<groupId>org.apache.geronimo.bundles</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8_2</version>
</dependency>
如果不导入上述包的话,会出现异常
java.lang.ClassNotFoundException: org.aspectj.weaver.reflect.ReflectionWorld$Reflection……
需要在 context.xml中导入 AOP 约束
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd"
首先配置好需要使用类的 bean
<bean id="peopleService" class="com.hukanmasheng.service.PeopleServiceImpl"/>
<bean id="afterLog" class="com.hukanmasheng.utils.AfterLog"/>
<bean id="beforeLog" class="com.hukanmasheng.utils.BeforeLog"/>
然后配置 aop 切面,共有三种方式如下:
- Spring AOP 原生接口:只需在context.xml 文件中配置,代码如下:
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.hukanmasheng.service.PeopleServiceImpl.*(..))"/>
<!–执行环绕增加–>
<aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
-
自定义类:需要先创建一个切点类,然后在配置文件中配置切点类。配置代码如下:
<bean id="logPointCut" class="com.hukanmasheng.pointcut.LogPointCut"/> <aop:config> <aop:aspect ref="logPointCut"> <aop:pointcut id="pointcut" expression="execution(* com.hukanmasheng.service.PeopleServiceImpl.*(..))"/> <aop:before method="before" pointcut-ref="pointcut"/> <aop:after method="after" pointcut-ref="pointcut"/> </aop:aspect> </aop:config>
切点类代码如下:
public class LogPointCut { public void before() { System.out.println("before 方法被执行了……"); } public void after() { System.out.println("after 方法被执行了……"); } }
-
注解方式:context.xml 中需要开启注解支持。
xml 文件配置如下:<!-- 方法三:通过注解方式--> <bean id="annoPointCut" class="com.hukanmasheng.pointcut.AnnoPointCut"/> <!-- 需要开启注解支持 --> <aop:aspectj-autoproxy/>
切点类代码如下:
@Aspect //注解标识该类是一个切面 public class AnnoPointCut { @Before("execution(* com.hukanmasheng.service.PeopleServiceImpl.*(..))") public void before() { System.out.println("通过注解方式执行了 before 方法……"); } @After("execution(* com.hukanmasheng.service.PeopleServiceImpl.*(..))") public void after() { System.out.println("通过注解方式执行了 after 方法……"); } @Around("execution(* com.hukanmasheng.service.PeopleServiceImpl.*(..))") public void around(ProceedingJoinPoint jp) throws Throwable { System.out.println(" 环绕前 "); Signature signature = jp.getSignature(); System.out.println("signature:"+signature); Object proceed = jp.proceed(); System.out.println(proceed); System.out.println(" 环绕后 "); } }