1、面向切面的定义自行百度
2、面向切面编程的应用场景自己想象,大概就是日志之类的地方
3、上面两句话基本是废话
实现方式一,在XML中声明切面
1、编写一个原始类
本例中show()方法就是切点。在一个大型项目中,许多个切点构成了切面,这些切面实际上是为了某些共同的东西而成为一个面的。
2、编写一个切面类
注意代码中的joinpoint.proceed(),这句话就是实际调用切点方法,也就是本例中的show()。如果切面类中定义了around通知,通知一定要加上这句话,否则要切点方法不会被调用!此处应该是一个坑,一定要记住,免得后面找bug到处都找不到。
3、配置XML
注意,上面的<bean id="audience" class="com.hsb.aop.Audience" />将切面类生命为一个bean,而<aop:config></aop:config>声明中引用了这个bean.简单解释一下<aop:config>声明中各句的意思。配置声明的时候,一定注意使用英文字符进行配置,不然会报很多稀奇古怪的错误,大致就是说切面无法使用或者其他什么的。
声明了一个切点(pointcut),后面声明的通知会引用。
通知一共有五种分别是<aop:before />、<aop:after />、<aop:after-returning />、<aop:after-throwing />、<aop:around />。根据其字面意思大概就能懂其应用场景,而around上面已经说过了,标识出切点位置,在切点前后做某些工作。
4、测试
上面的代码使用自动注入生成一个Perform实例,在测试方法中调用切点方法show().
5、Console打印结果
从Console的打印结果中,我们可以猜测出五种通知的具体用法
6、Maven工程一定要添加依赖
如果不添加上述依赖,极有可能会测试报错。
实现方式二,注解切面
1、编写一个原始类
2、编写一个切面类
@Aspect将此类声明为切面类,@Component将此类声明为bean放到spring容器中,@Pointcut将下面的performance声明为一个切点,并将Perform中的show()方法进行了关联。execution(* com.hsb.beans.Perform.show(..))的意思是,执行此方法时,忽略返回值,参数类型和个数忽略。还可以更加简写,用于匹配合适的方法,譬如对Perform类的全部方法进行匹配就是com.hsb.beans.Perform.*。
3、配置xml
可以看见此处就没有使用<aop:config />声明,而是使用<aop:aspectj-autoproxy proxy-target-class="true" />。这句话的意思是自动在spring上下文中创建一个AnnotationAwareAspectJAutoProxyCreator类,它会自动代理一些bean,这些bean的方法需要与使用@Aspect注解的bean中所定义的切点相匹配,而这些切点又是使用@Pointcut注解定义出来的。proxy-target-class="true"的意思是使用基于类的代理使用 cglib库,如果为false则使用jdk自带的基于接口的代理
4、测试
5、Console打印结果
如上所示,完全是一样的效果。可以看出使用注解减少了很多工作,不容易出错,各个组件间的耦合度降低了。试想,如果一个大型项目中有很多切面,切点,如果全部去xml中配置,将会是一项极为艰苦的工作,但是如果使用注解就可以做很少的工作完成这一切。
后记一、使用注解时一定要使用@component或者@Repository、@Controller、@Service中一个去声明,将切面类放入到spring容器中,不然就去xml中显式写一个bean,不然的话就会报错,无法实现切面功能。