.注解实现
架包
aspectjrt.jar
asm-2.2.3.jar
asm-commons-2.2.3.jar
asm-util-2.2.3.jar
spring.jar
cglib-nodep-2.1_3.jar
log4j-1.2.11.jar
commons-logging-1.0.4.jar
配置AOP.xml
<?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">
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean id="shopwaiterProxy" class="aopaspectjauto.ShopWaiter" />
<bean class="aopaspectjauto.TestAspect" />
</beans>
1.接口NeedTest 注解接口
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface NeedTest {
boolean value() default false;
}
2.类ShopWaiter
public class ShopWaiter implements Waiter {
@NeedTest(value = false)
public void sayHello(String name) {
System.out.println("say hello to:" + name);
}
@NeedTest(value = true)
public void sayhi() {
System.out.println("say hi to Bill");
}
}
3.类TestAspect 注解界面
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class TestAspect {
@AfterReturning("@annotation(NeedTest)") //注解表达式
public void needTestFun() {
System.out.println("after needTestFun() executed");
}
@Before("@annotation(NeedTest)")
public void needTestFu() {
System.out.println("before needTestFun() executed");
}
}
4.接口Waiter
public interface Waiter {
void sayHello(String name);
void sayhi();
}
5.使用Main
import java.lang.reflect.Method;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("/AOP.xml");
Waiter waiter = (ShopWaiter) ctx.getBean("shopwaiterProxy");
waiter.sayHello("========");
waiter.sayhi();
}
public static void testComment() {
Class clazz = ShopWaiter.class;
Method[] methods = clazz.getDeclaredMethods();
for (Method m : methods) {
NeedTest nt = m.getAnnotation(NeedTest.class);
if(nt != null){
if(nt.value()){
System.out.println(m.getName()+"()需要测试");
}else{
System.out.println(m.getName()+"()不需要测试");
}
}
}
}
}