返回介绍

7.4 静态 AOP 使用示例

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

加载时织入(Load-Time Weaving,LTW)指的是在虚拟机载入字节码文件时动态织入 AspectJ 切面。Spring 框架的值添加为 AspectJ LTW 在动态织入过程中提供了更细粒度的控制。使用 Java(5+)的代理能使用一个叫“Vanilla”的 AspectJ LTW,这需要在启动 JVM 的时候将某个 JVM 参数设置为开。这种 JVM 范围的设置在一些情况下或许不错,但通常情况下显得有些粗颗粒。而用 Spring 的 LTW 能让你在 per-ClassLoader 的基础上打开 LTW,这显然更加细粒度并且对“单 JVM 多应用”的环境更具意义(例如在一个典型应用服务器环境中)。另外,在某些环境下,这能让你使用 LTW 而不对应用服务器的启动脚本做任何改动,不然则需要添加-javaagent:path/to/aspectjweaver.jar 或者(以下将会提及的)-javaagent:path/to/Spring-agent.jar。开发人员只需简单修改应用上下文的一个或几个文件就能使用 LTW,而不需依靠那些管理者部署配置,比如启动脚本的系统管理员。

我们还是以之前的 AOP 示例为基础,如果想从动态代理的方式改成静态代理的方式需要做如下改动。

(1)Spring 全局配置文件的修改,加入 LWT 开关。

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

 <context:load-time-weaver />

</beans>

(2)加入 aop.xml。在 class 目录下的 META-INF(没有则自己建立)文件夹下建立 aop.xml,内容如下:

<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">

<aspectj>

 <weaver>

   <!-- only weave classes in our application-specific packages -->

   <include within="test.*" />

 </weaver>

 <aspects>

   <!-- weave in just this aspect -->

   <aspect name="test.AspectJTest" />

 </aspects>

</aspectj>

主要是告诉 AspectJ 需要对哪个包进行织入,并使用哪些增强器。

(3)加入启动参数。如果是在 Eclipse 中启动的话需要加上启动参数,如图 7-3 所示。

figure_0212_0038

图 7-3 eclipse 使用 AspectJ 的配置

(4)测试。

public static void main(String[] args) {

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

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

 bean.testBeanM();

}

测试结果与动态 AOP 并无差别,打印出结果:

beforeTest

test

afterTest

发布评论

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