Spring框架之AOP编程

1.介绍:AOP:面向切面编程,采取横向抽取机制,取代了传统纵向继承体系重复性代码。
2.AOP实现原理
aop底层将采用代理机制进行实现。
接口 + 实现类:spring采用 jdk 的动态代理Proxy。
实现类:spring 采用 cglib字节码增强。
3.AOP术语
1.target目标类:需要被代理的类。例如:UserService
2. Joinpoint连接点:所谓连接点是指那些可能被拦截到的 方法。例如:所有的方法
3. PointCut切入点:已经被增强的连接点。例如:addUser()
4. advice通知/增强,增强代码。例如:after、before
5. Weaving织入:是指把增强advice应用到目标对象target来创建新的代理对象proxy的过程.
6. proxy代理类
7. Aspect切面:是切入点pointcut和通知advice的结合
一个线是一个特殊的面。
一个切入点和一个通知,组成成一个特殊的面。
4.spring aop编程
4.1依赖jar包
在这里插入图片描述
4.2目标类

public interface UserService {
	
	public void addUser();
	public void updateUser();
	public void deleteUser();
}

4.3切面类

public class MyAspect implements MethodInterceptor {

	@Override
	public Object invoke(MethodInvocation mi) throws Throwable {
		
		System.out.println("前3");
		
		//手动执行目标方法
		Object obj = mi.proceed();
		
		System.out.println("后3");
		return obj;
	}
}

4.4测试类

@Test
	public void demo01(){
		String xmlPath = "com/selan/b_factory_bean/beans.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		
		//获得代理类
		UserService userService = (UserService) applicationContext.getBean("proxyServiceId");
		userService.addUser();
		userService.updateUser();
		userService.deleteUser();
	}

4.5spring配置文件

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       					   http://www.springframework.org/schema/beans/spring-beans.xsd
       					   http://www.springframework.org/schema/aop 
       					   http://www.springframework.org/schema/aop/spring-aop.xsd">
	<!-- 1 创建目标类 -->
	<bean id="userServiceId" class="com.selan.c_spring_aop.UserServiceImpl"></bean>
	<!-- 2 创建切面类(通知) -->
	<bean id="myAspectId" class="com.selan.c_spring_aop.MyAspect"></bean>
	<!-- 3 aop编程  -->
	<aop:config proxy-target-class="true">
		<aop:pointcut expression="execution(* com.selan.c_spring_aop.*.*(..))" id="myPointCut"/>
		<aop:advisor advice-ref="myAspectId" pointcut-ref="myPointCut"/>
	</aop:config>
</beans>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值