- 前言
- 第一部分 核心实现
- 第 1 章 Spring 整体架构和环境搭建
- 第 2 章 容器的基本实现
- 第 3 章 默认标签的解析
- 第 4 章 自定义标签的解析
- 第 5 章 bean 的加载
- 第 6 章 容器的功能扩展
- 第 7 章 AOP
- 第二部分 企业应用
- 第 8 章 数据库连接 JDBC
- 第 9 章 整合 MyBatis
- 第 10 章 事务
- 第 11 章 SpringMVC
- 第 12 章 远程服务
- 第 13 章 Spring 消息
7.4 静态 AOP 使用示例
加载时织入(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 所示。

图 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
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论