- 前言
- 第一部分 核心实现
- 第 1 章 Spring 整体架构和环境搭建
- 第 2 章 容器的基本实现
- 第 3 章 默认标签的解析
- 第 4 章 自定义标签的解析
- 第 5 章 bean 的加载
- 第 6 章 容器的功能扩展
- 第 7 章 AOP
- 第二部分 企业应用
- 第 8 章 数据库连接 JDBC
- 第 9 章 整合 MyBatis
- 第 10 章 事务
- 第 11 章 SpringMVC
- 第 12 章 远程服务
- 第 13 章 Spring 消息
7.1 动态 AOP 使用示例
(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,那么我们的分析就从这句注解开始。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论