AspectJ框架
概念
- AspectJ是一个面向切面的框架,它扩展了Java语言。AspectJ定义了AOP语法,它有一个专门的编译器用来生成遵守Java字节编码规范的Class文件。
- AspectJ(也就是AOP)的动机是发现那些使用传统的编程方法无法很好处理的问题。考虑一个要在某些应用中实施安全策略的问题。安全性是贯穿于系统所有模块间的问题,每个模块都需要应用安全机制才能保证整个系统的安全性,很明显这里的安全策略的实施问题就是一个横切关注点,使用传统的编程解决此问题非常的困难而且容易产生差错,这就正是AOP发挥作用的时候了。@AspectJ 使用了Java5 的注解,可以将切面声明为普通的Java类。
例子:
-
猴子偷桃园丁看桃的例子
-
这是园丁类,就模拟是一个切面
import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; /* * * 这是一个切面,园丁守护桃园,实现前置通知,后置通知 * */ //这一个切面注解,告诉扫描器这是一个切面 @Aspect public class Gardener { //当执行这个方法时就触发通知。 @Pointcut("execution(* com.wdhcr.StealingPeach.Monkeys.stealingPeach(..))") public void catchMonkey(){} //前置通知 @Before(value = "catchMonkey()") public void catchBefore(){ System.out.println("有猴子来了,我们准备抓他"); } @After(value = "catchMonkey()&&args(name,..)") public void catchAfter(String name){ System.out.println("我们抓到猴子,"+name+" 将他暴打一顿"); } }
-
猴子类,模拟是主业务类
/* * 这是主业务类,猴子偷桃 * * */ public class Monkeys { public void stealingPeach(String name){ System.out.println("我是猴子,我叫"+name+"我来偷桃"); } }
-
这是配置文件
<?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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <!-- //注入我们的bean--> <bean id="monkey" class="com.wdhcr.StealingPeach.Monkeys"></bean> <bean id="gardener" class="com.wdhcr.StealingPeach.Gardener"></bean> <!-- 设一下让spring支持aspectj--> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>
-
测试类代码
import org.springframework.context.support.ClassPathXmlApplicationContext;
/*
* 这是测试抓猴子的类,也是测试aop面向切面编程的例子
* */
public class TestSp {
public static void main(String[] args) {
ClassPathXmlApplicationContext classPathXmlApplicationContext =
new ClassPathXmlApplicationContext("monkeyBean.xml");
Monkeys monkey = (Monkeys) classPathXmlApplicationContext.getBean("monkey");
//让猴子开始偷桃
monkey.stealingPeach("孙悟空");
}
}
-
运行结果
-
以上就是一个ApectJ在Spring框架中的小小的使用案例。