在开始之前先来一篇aop的介绍http://blog.csdn.net/Intlgj/article/details/5671248 aop(面向切面编程)不同于oop(面向对象编程),aop在实际开发中运用的还是比较常见的,aop能干什么 权限控制、事务控制、动态切入(日志)等(这也是我面试被问到的一个问题)
现在我假定一个场景,大家都爱吃吃喝喝玩玩我定义一个class类(MethodService)里面有 吃的方法(eat)也有看电影的方法(movie),吃饭看电影都要钱的,你在看电影吃饭之前你不得考虑身上有没有钱。参考代码如下:
第一步创建一个maven工程工程结构如下
第二步添加aop需要的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.burning</groupId>
<artifactId>spring4_aop</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- spring aop支持-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<!-- aspectj 支持 -->
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.5.4</version>
</dependency>
</dependencies>
</project>
第三步创建四个类
这就是一个人的行为的类 里面有吃饭和看电影的方法
注解详细介绍:
@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的支持
第四步图解
看图就能理解其实在看电影吃饭你都要确定自己有没有钱(这也是两个行为执行之前共同的地方),比如我们在实际开发当中一些操作判断有没有操作的权限的时候可以用aop的去做权限控制。其实也就是执行一个方法之前的操作。不仅有@Before 有@After @Around可以这连个注解参考:http://outofmemory.cn/code-snippet/3025/spring-AOP-Around-Before-After-differentiate
源码地址:https://github.com/BurIngYou/spring4_aop