上篇的例子,自动装配和自动检测Bean是使用注解的方式处理的,而面向切面编程是使用aop标签处理的,给我感觉就像中西医参合一样。

现在就来优化优化,全部使用注解的方式处理。

1、工程图:

 

利用例子来理解spring的面向切面编程(使用@Aspect)

 

 2、Protecter的修改如下,Protecter声明了切点和通知,因此不需要在xml中配置切点和通知了。

package com.test.demo.protect;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.test.demo.stolen.Peaces;

/**
 * 守护者,是一个切面
 * TODO Comment of Protecter
 *
 
*/
@Component("protecter")
@Aspect
public class Protecter {
    @Pointcut("execution(* com.test.demo.stolen.Stolen.stolens(String,com.test.demo.stolen.Peaces)) and args(name,peace)")
    //stolens()是切点的一个名称,类似于xml配置时指定的id一样
    public void stolens(){
    }

    @Before("stolens() && args(name,peace)")
    public void before(String name,Peaces peace){
        System.out.println("守护者在守护桃子"+peace.getName()+"...");
    }
    
    @After("stolens() && args(name,peace)")
    public void after(String name,Peaces peace){
        System.out.println("守护者发现猴子"+name+"在偷桃子"+peace.getName());
    }
}

 2、Stolen 接口,未做任何修改:

package com.test.demo.stolen;

public interface Stolen {
    /**
     * 偷桃子
     * 
     * @date 2014-4-1
     
*/
    public void stolens(String name,Peaces peace);
}
View Code

相关文章:

  • 2021-10-11
  • 2021-05-20
  • 2021-11-29
  • 2021-09-25
  • 2022-12-23
  • 2021-06-16
  • 2022-12-23
  • 2021-12-13
猜你喜欢
  • 2022-12-23
  • 2021-11-23
  • 2021-12-07
  • 2021-11-26
  • 2021-11-30
  • 2021-10-17
  • 2021-12-19
相关资源
相似解决方案