- 前面讲的是使用AspectJ来实现AOP编程,这里的例子是在spring框架通过aspectJ实现AOP编程。
- 要继续往下看需要你把aspectJ先装好,怎么装在进阶(15)有介绍。
- 在安装好aspctJ之后,把安装目录下lib文件夹下的aspectjrt.jar和aspectjweaver.jar添加为lib,怎么添加就不仔细说了哈。
- 代码呀代码,这里呢是实现在运行Hello的hello方法之前调用AutoAspect的before方法。
- 一个一个讲解,首先是beans.xml.在beans.xml中导入了aop支持,并且使用注解来配置bean和annontationd。
<?xml version="1.0" encoding="GBK"?> <!--要导入zop支持--> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"> <!-- 指定自动搜索Bean组件、自动搜索切面类 --> <context:component-scan base-package="before_package"> <context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/> </context:component-scan > <!-- 启动@AspectJ支持 --> <aop:aspectj-autoproxy/> </beans>
Hello,一个普通的类,要注意的是它并不知道自己在执行的过程中有被增强了。
package before_package; import org.springframework.stereotype.Component; @Component("hello") public class Hello { public void sayHello(String a, String b){ System.out.println(a + " ," + b); } }
然后是使用了@Aspect注解的类,用法和使用Aspect差不多,指定对那些类的哪些方法进行如何的增强
@Aspect public class AuthAspect { @After("execution(* before_package.*.*(..))") public void before(){ System.out.println("before"); } }
测试类
package test_spring_aop_package; import before_package.Hello; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { public static void main(String []args){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); Hello hello = applicationContext.getBean("hello", Hello.class); hello.sayHello(); } }
还有就是在方法执行之后的增强处理,就是把Before换成After就好了,原理是一样的,就不贴代码了。
- 一个一个讲解,首先是beans.xml.在beans.xml中导入了aop支持,并且使用注解来配置bean和annontationd。