Spring AOP 配置

基础篇
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...

                                       --完--

 

 

 
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值