AOP操作的AspectJ注解方式,小编在前面的文章:Spring — AOP 操作 - AspectJ注解 有介绍到,感兴趣的小伙伴可以去翻看一下。今天小编给大家带来的是,如何通过AspectJ配置文件方式操作AOP。下面,跟着小编我,一起往下看吧!
1,编写被增强类,即连接点(aop术语)
public class Customer {
//自定义被增强方法
public void buy(){
System.out.println("Customer buy..");
}
}
2,编写增强类,即aop代码所在类
public class CustomerProxy {
/**
* 下面几个方法分别表示aop增强的几类
*/
public void before(){
System.out.println("customerProxy 前置增强");
}
public void after(){
System.out.println("customerProxy 后置增强");
}
public void afterReturning(){
System.out.println("customerProxy 后置返回增强");
}
public void throwable(){
System.out.println("customerProxy 异常增强");
}
}
3,编写xml配置文件:AopConfig.xml。文件头部包括 自定义 xmlns:aop 的编写,如果有疑惑的小伙伴,可以翻看小编之前的文章:Spring — IOC 容器 之 Bean管理XML方式(外部属性文件) 即可理解
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.xsd">
<!-- 创建bean-->
<!-- 被增强类-->
<bean id="customer" class="com.chaoge.nacos.demo.test.spring.entity.Customer"/>
<!-- 增强类 即aop代码所在类-->
<bean id="customerProxy" class="com.chaoge.nacos.demo.test.spring.entity.CustomerProxy"/>
<!-- 配置aop增强-->
<aop:config>
<!-- 配置切入点 id标签为自定义的值,expression 指明切入点表达式-->
<aop:pointcut id="point" expression="execution(* com.chaoge.nacos.demo.test.spring.entity.Customer.buy(..))"/>
<!-- 配置切面 ref标签指向增强类-->
<aop:aspect ref="customerProxy">
<!-- 配置前置增强 method标签指明增强类中前置增强方法;pointcut-ref标签指明切入点-->
<aop:before method="before" pointcut-ref="point"/>
<!-- 配置后置增强-->
<aop:after method="after" pointcut-ref="point"/>
<!-- 配置后置返回增强-->
<aop:after-returning method="afterReturning" pointcut-ref="point"/>
<!-- 配置异常增强-->
<aop:after-throwing method="throwable" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
</beans>
4,使用
public class BeanTest {
@Test
public void test9(){
ApplicationContext context = new
ClassPathXmlApplicationContext("com/chaoge/nacos/demo/test/spring/beanConfig/AopConfig.xml");
Customer customer = context.getBean("customer", Customer.class);
customer.buy();
}
}
5,输出
D:\jdk\jdk1.8.0_171\bin\java.exe
customerProxy 前置增强
Customer buy..
customerProxy 后置增强
customerProxy 后置返回增强
4,看到这里,大家都明白了如何通过AspectJ配置文件实现AOP操作了吧!如果这篇文章有帮助到你,麻烦再动一动你的小手,给小编来个赞和关注吧!谢谢!