SpringBoot学习(四)—AOP切面编程

在开始之前先来一篇aop的介绍http://blog.csdn.net/Intlgj/article/details/5671248  aop(面向切面编程)不同于oop(面向对象编程),aop在实际开发中运用的还是比较常见的,aop能干什么 权限控制、事务控制、动态切入(日志)等(这也是我面试被问到的一个问题)

现在我假定一个场景,大家都爱吃吃喝喝玩玩我定义一个class类(MethodService)里面有 吃的方法(eat)也有看电影的方法(movie),吃饭看电影都要钱的,你在看电影吃饭之前你不得考虑身上有没有钱。参考代码如下:

第一步创建一个maven工程工程结构如下

SpringBoot学习(四)—AOP切面编程_第1张图片

第二步添加aop需要的依赖



    4.0.0

    com.burning
    spring4_aop
    1.0-SNAPSHOT
    
    
        
            org.springframework
            spring-context
            4.1.6.RELEASE
        
        
        
            org.springframework
            spring-aop
            4.1.9.RELEASE
        

        
        
            aspectj
            aspectjrt
            1.5.4
        
        
            aspectj
            aspectjweaver
            1.5.4
        

    


第三步创建四个类

SpringBoot学习(四)—AOP切面编程_第2张图片

这就是一个人的行为的类 里面有吃饭和看电影的方法


SpringBoot学习(四)—AOP切面编程_第3张图片


 
  


SpringBoot学习(四)—AOP切面编程_第4张图片

注解详细介绍:

@Aspect//定义切面
@Before("execution(* com.burning.aop.MethodService.*(..))")//execution切入的路径(在MthodService中的方法执行之前先执行这个)
@Component:定义Spring管理Bean
@AspectJ风格的切面可以通过@Compenent注解标识其为Spring管理Bean,而@Aspect注解不能被Spring自动识别并注册为Bean,必须通过@Component注解来完成
@Configuration//配置类
@ComponentScan("com.burning.aop")//扫描com.burning.aop所有的bean
@EnableAspectJAutoProxy//开启Spring对aop的支持



SpringBoot学习(四)—AOP切面编程_第5张图片



第四步图解


看图就能理解其实在看电影吃饭你都要确定自己有没有钱(这也是两个行为执行之前共同的地方),比如我们在实际开发当中一些操作判断有没有操作的权限的时候可以用aop的去做权限控制。其实也就是执行一个方法之前的操作。不仅有@Before 有@After @Around可以这连个注解参考:http://outofmemory.cn/code-snippet/3025/spring-AOP-Around-Before-After-differentiate


SpringBoot学习(四)—AOP切面编程_第6张图片


源码地址:https://github.com/BurIngYou/spring4_aop


你可能感兴趣的:(SpringBoot)