Spring Aop详解

什么是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>

运行即可看到效果

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱写程序的白羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值