AOP入门
aop–aspect oriented program 面向切面编程 能够监听对象方法的调用前、中、后,在方法调用的不同阶段添加其他的操作
需求:创建事务类classA和监听类classB,在classA中某一方法执行前,执行后调用classB中对应的方法
步骤:
- pom.xml添加aop相关依赖
- applicationContext.xml添加上aop配置,监听类和监听切入点
- 创建被监听的类ProductService,监听类LoggerAspect,以及测试类
pom.xml aop相关依赖
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
<!-- <scope>runtime</scope>-->
</dependency>
<!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.3</version>
</dependency>
applicationContext.xml配置文件
<!--注意添加aop-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
</beans>
<bean name="productService" class="service.ProductService"/>
<bean name="loggerAspect" class="aspect.LoggerAspect"/>
<aop:config>
<aop:pointcut id="productServicePoint" expression="execution(* service.ProductService.*(..))"/>
<aop:aspect id="loggerAspectAspect" ref="loggerAspect">
<aop:after method="doAfter" pointcut-ref="productServicePoint"/>
<aop:before method="doBefore" pointcut-ref="productServicePoint"/>
</aop:aspect>
</aop:config>
被监听的类ProductService,监听类LoggerAspect
package service;
public class ProductService {
public void doSomeService(){
System.out.println("do someService now.....");
}
}
package aspect;
public class LoggerAspect {
public void doBefore(){
System.out.println("doBefore");
}
public void doAfter(){
System.out.println("doAfter");
}
}
package hello;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MessageServiceTest {
@Test
public void test(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
MessagePrinter printer = context.getBean(MessagePrinter.class);
printer.output();
}
}
运行结果:
参考: