什么是Aop?
1.Aop(Aspect Oriented Programming)是一种面向切面的编程,AOP是OOP(面向对象编程)的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
2.经典应用:事务管理、性能监视、安全检查、缓存 、日志等。
项目中使用Aop 最大的好处就是不需要动其他地方的代码,直接在原基础上添加新功能就行了
代码演示:
1.第一步导入jar包
2.在项目包中src创建aop包、service包、还有test测试包,并且创建resource文件夹
1.aop中创建FirstAop.java类
2.service中创建StudentServce.java
3.test包中创建Test.java类
4.resource文件夹创建applicationContext.xml
1.在Aop包中FirstAop类代码如下
package aop;
import org.aspectj.lang.JoinPoint;
public class FirstAop {
/*即将加进去的功能*/
public void eat() {
System.out.println("最前学生在吃饭");
}
public void sleep(JoinPoint jp,String result) {
// TODO Auto-generated method stub
System.out.println("最后学生学完睡觉");
System.out.println("返回值是"+result);
}
public void play(){
System.out.println("最终在玩");
}
}
2.service中StudentServce内容如下
package service;
public class StudentService {
public String study() {
System.out.println("学生在学习!");
return "aa";
}
}
3.在测试类中test中
package service;
public class StudentService {
public String study() {
System.out.println("学生在学习!");
return "aa";
}
}
4.resource文件夹中applicationContext.xml内容
<?xml version="1.0" encoding="UTF-8"?>
<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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<!--旧功能 -->
<bean class="service.StudentService" id="aa">
</bean>
<!--xml中放入新功能 -->
<bean class="aop.FirstAop" id="aop">
</bean>
<!-- 切点-->
<aop:config>
<aop:aspect ref="aop"> <!-- 告诉需要切的人 -->
<aop:pointcut expression="execution(public String study())" id="pc"/><!-- 切点 -->
<aop:before method="eat" pointcut-ref="pc"/><!--前置增强 -->
<aop:after-returning method="sleep" pointcut-ref="pc" returning="result"/><!-- 后置增强 -->
<aop:after method="play" pointcut-ref="pc"/><!-- 最终增强 -->
</aop:aspect>
</aop:config>
</beans>
运行即可看到效果