基本接口与实现AOP

3.2.1 明确需求

在某个方法上加上@FddLog,就会在执行这个方法的前后,自动输出相应的信息。下面以把大象放进冰箱为例子进行演示:

3.2.2 基本接口和实现


  1. public interface ElephentToRe{ 
  2.   public void toRe(); 

实现类如下:


  1. public class ElephentToReImpl implements ElephentToRe{ 
  2.   public void toRe() { 
  3.     System.out.println("把大象放冰箱"); 
  4.   } 

3.2.3 定义切面和通知


  1. public class ElephentToReHelper{ 
  2.     public void beforeElephentToRe(){ 
  3.         System.out.println("把冰箱门打开"); 
  4.     } 
  5.     public void afterElephentToRe(){ 
  6.         System.out.println("把冰箱门关上"); 
  7.     } 

配置就好了


  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" 
  3.   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 
  4.   xsi:schemaLocation="http://www.springframework.org/schema/beans 
  5.   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
  6.   http://www.springframework.org/schema/aop 
  7.   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> 
  8.   <!— 定义通知内容,也就是切入点执行前后需要做的事情 –> 
  9.   <bean id="elephentToReHelper" class="com.fdd.bean.ElephentToReHelper"></bean> 
  10.   <!— 定义被代理者 –> 
  11.   <bean id="elephentToReImpl" class="com.fdd.bean.ElephentToReImpl"></bean> 
  12.   <aop:config> 
  13.     <aop:aspect ref="elephentToReHelper"
  14.       <aop:before method="beforeElephentToRe" pointcut="execution(* *.toRe(..))" /> 
  15.       <aop:after method="afterElephentToRe" pointcut="execution(* *.toRe(..))" /> 
  16.     </aop:aspect> 
  17.   </aop:config> 
  18. </beans> 

3.2.4 测试看效果


  1. public class Test { 
  2.   public static void main(String[] args){ 
  3.     @SuppressWarnings("resource"
  4.     ApplicationContext appCtx = new FileSystemXmlApplicationContext("application.xml"); 
  5.     ElephentToRe elephentToReImpl = (ElephentToRe)appCtx.getBean("elephentToReImpl"); 
  6.     elephentToReImpl.toRe(); 
  7.   } 

上面的这种方法是通过纯粹的POJO切面来完成的。实现方式也比较简单。

4 我对AOP思想的看法

任何新技术的出现都是为了解决目前开发中存在的某些痛点。对于aop来说,其主要是把一些功能代码进行抽象封装,和主业务逻辑代码进行剥离。在需要的地方进行织入即可。

我的看法是

(1)在平时开发代码的时候,完全可以把一些常见的,常用的功能代码进行封装,尽量做到动态配置。不同的功能模块只需要进行织入即可。

(2)定义业务逻辑的模板,比如说如果要解决某一个业务功能,如果页面类似,可以按照基本的框架进行组合,然后使用配置平台进行可控化配置即可。

【声明】:芜湖站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

相关文章