基础篇
1、理解AOP
在不同的类方法中,为了执行相同的逻辑,设定了许多相同的插入点。这些点构成了一个切面,一刀切入到这些类方法中。
2、理解Aspect
Aspect是对系统中横切面关注点逻辑进行模块化封装的AOP概念实体。
包含多个Pointcut和Advice。
3、理解名词
1) Joinpoint
插入到方法中的点。
2)Pointcut
Joinpoint 构成的切面。
3)Advice
需要在Joinpoint出执行的逻辑。
配置篇
一、所需要的jar包
这是使用spring3.0.4时,所用到的包。
aopalliance-1.0.jar
aspectjrt.jar
aspectjweaver.jar
commons-logging-1.1.jar
org.springframework.aop-3.0.4.RELEASE.jar
org.springframework.asm-3.0.4.RELEASE.jar
org.springframework.aspects-3.0.4.RELEASE.jar
org.springframework.beans-3.0.4.RELEASE.jar
org.springframework.context-3.0.4.RELEASE.jar
org.springframework.core-3.0.4.RELEASE.jar
org.springframework.expression-3.0.4.RELEASE.jar
注:其中context包依赖beans包。
二、配置出现了异常
1) 这是指该构造函数缺少了BeanException异常包。
The constructor ClassPathXmlApplicationContext(String) refers to the missing type BeanException;
所以我们添加了org.springframework.beans-3.0.4.RELEASE.jar
2)不能代理目标对象。这和java的动态代理机制有关。
Exception:
Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces
解决方法:
1、将目标对象也就是要代理的对象bean,去实现一个接口IBean;
2、添加cglib2包。
代码如下:
//这是bean
package com.beans;
public interface IBean {
public void fry();
public void cook();
public void stew();
}
package com.beans;
public class BroadBean implements IBean {
public void fry(){
System.out.println("这是炒的方法");
}
public void stew() {
System.out.println("这是煮的方法");
}
public void cook() {
System.out.println("这是烹的方法");
}
}
//这是切面
@Aspect
public class BroadBeanInterceptor {
@Pointcut("execution(* com.beans.BroadBean.*(..))")
public void eatBean() {
System.out.println("I am eating...");//Joinpoint 不会执行
}
@Before("eatBean()")
public void hitBean() {
System.out.println("I am hitting...");
}
@Around("eatBean()")
public Object perofrmanceTrace(ProceedingJoinPoint joinpoint) throws Throwable {
StopWatch watch = new StopWatch();
try{
watch.start();
return joinpoint.proceed();
} finally {
watch.stop();
}
}
@After("eatBean()")
public void pick() {
System.out.println("I am picking...");
}
}
//这是测试
public class AOPTest {
@Test
public void testAOP() {
ApplicationContext appContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
IBean b = (IBean) appContext.getBean("broadBean");
b.cook();
b.fry();
}
}
输出为:
I am hitting...
这是烹的方法
I am picking...
I am hitting...
这是炒的方法
I am picking...
--完--