返回介绍

7.1 动态 AOP 使用示例

发布于 2025-04-22 22:09:13 字数 3098 浏览 0 评论 0 收藏

(1)创建用于拦截的 bean。

在实际工作中,此 bean 可能是满足业务需要的核心逻辑,例如 test 方法中可能会封装着某个核心业务,但是,如果我们想在 test 前后加入日志来跟踪调试,如果直接修改源码并不符合面向对象的设计方法,而且随意改动原有代码也会造成一定的风险,还好接下来的 Spring 帮我们做到了这一点。

public class TestBean{

  private String testStr = "testStr";

  public String getTestStr() {

   return testStr;

 }

  public void setTestStr(String testStr) {

   this.testStr = testStr;

 }

  public void test(){

  System.out.println("test");

 }

}

(2)创建 Advisor。

Spring 中摒弃了最原始的繁杂配置方式而采用 @AspectJ 注解对 POJO 进行标注,使 AOP 的工作大大简化,例如,在 AspectJTest 类中,我们要做的就是在所有类的 test 方法执行前在控制台中打印 beforeTest,而在所有类的 test 方法执行后打印 afterTest,同时又使用环绕的方式在所有类的方法执行前后再次分别打印 before1 和 after1。

@Aspect

public class AspectJTest {

 @Pointcut("execution(* *.test(..))")

  public void test(){

 }

 @Before("test()")

  public void beforeTest(){

  System.out.println("beforeTest");

 }

 @After("test()")

  public void afterTest(){

  System.out.println("afterTest");

 }

 @Around("test()")

  public Object arountTest(ProceedingJoinPoint p){

  System.out.println("before1");

   Object o=null;

   try {

    o = p.proceed();

   } catch (Throwable e) {

   e.printStackTrace();

  }

  System.out.println("after1");

   return o;

 }

}

(3)创建配置文件。

XML 是 Spring 的基础。尽管 Spring 一再简化配置,并且大有使用注解取代 XML 配置之势,但是无论如何,至少现在 XML 还是 Spring 的基础。要在 Spring 中开启 AOP 功能,还需要在配置文件中作如下声明:

<?xml version="1.0" encoding="UTF-8"?>

<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"

 xmlns:context="http://www.Springframework.org/schema/context"

 xsi:schemaLocation="http://www.Springframework.org/schema/beans

  http://www.Springframework.org/schema/beans/Spring-beans-3.0.xsd

  http://www.Springframework.org/schema/aop

  http://www.Springframework.org/schema/aop/Spring-aop-3.0.xsd

  http://www.Springframework.org/schema/context

   http://www.Springframework.org/schema/context/Spring- context-

  3.0.xsd

 ">

<aop:aspectj-autoproxy />

<bean id="test" class="test.TestBean"/>

<bean class="test.AspectJTest"/>

</beans>

(4)测试。

经过以上步骤后,便可以验证 Spring 的 AOP 为我们提供的神奇效果了。

public static void main(String[] args) {

  ApplicationContext bf = new ClassPathXmlApplicationContext("aspectTest.xml");

  TestBean bean=(TestBean) bf.getBean("test");

 bean.test();

}

不出意外,我们会看到控制台中打印了如下代码:

beforeTest

before1

test

afterTest

after1

Spring 实现了对所有类的 test 方法进行增强,使辅助功能可以独立于核心业务之外,方便与程序的扩展和解耦。

那么,Spring 究竟是如何实现 AOP 的呢?首先我们知道,Spring 是否支持注解的 AOP 是由一个配置文件控制的,也就是<aop:aspectj-autoproxy />,当在配置文件中声明了这句配置的时候,Spring 就会支持注解的 AOP,那么我们的分析就从这句注解开始。

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。