上篇的例子,自动装配和自动检测Bean是使用注解的方式处理的,而面向切面编程是使用aop标签处理的,给我感觉就像中西医参合一样。
现在就来优化优化,全部使用注解的方式处理。
1、工程图:
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());
}
}
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);
}
public interface Stolen {
/**
* 偷桃子
*
* @date 2014-4-1
*/
public void stolens(String name,Peaces peace);
}