日期:2014-05-17 浏览次数:20860 次
package aspect2; import java.lang.reflect.Method; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; /** * @author zhuc * */ @Aspect @Component public class Aspect2 { @Pointcut(value = "@annotation(aspect2.Log)") private void pointCut() { } @After(value = "pointCut()") public void doAfter() throws ClassNotFoundException { Class cls = Class.forName("aspect2.Service"); Method[] method = cls.getMethods(); for (int i = 0; i < method.length; i++) { boolean otherFlag = method[i].isAnnotationPresent(Log.class); if (otherFlag) { Log log = method[i].getAnnotation(Log.class); System.out.println(log.desc()); } } System.out.println("doAfter......"); } }
?
?
package aspect2; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author zhuc * */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Log { String desc() default ""; }
?
?
?
package aspect2; /** * @author zhuc * */ public class Service { @Log(desc = "添加Log") public void addLog(String name) { System.out.println(name); } }
?
?
aspect2.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" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> <context:component-scan base-package="aspect2" /> <aop:aspectj-autoproxy /> <bean id="service" class="aspect2.Service" /> </beans>
?
?
?
package aspect2; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author zhuc * */ public class Test { /** * @param args */ public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext( "aspect2/aspect2.xml"); Service s = (Service) ac.getBean("service"); s.addLog("新的日志"); } }
?
?
?
运行结果:
?
新的日志
添加Log
doAfter......