编程方式实现Spring的aop

一、UserService接口

<span style="font-size:18px;">package com.seven.spring.m_aop_helloworld;

public interface UserService {
   void queryUsers();
   
   void saveUser();
   
   void deleteUser();
}</span>
二、UserServiceImpl实现类

<span style="font-size:18px;">package com.seven.spring.m_aop_helloworld;

public class UserServiceImpl implements UserService{
	@Override
	public void queryUsers() {
		System.out.println("查询一个User");
	}
	@Override
	public void saveUser() {
		System.out.println("保存一个User");		
	}
	@Override
	public void deleteUser() {
		System.out.println("删除一个User");		
	}
}</span>
这种是有接口的方式Spring会按照JDK动态代理的方式来实现

三、拦截方法的类LogAdvice实现了MethodInterceptor接口,

<span style="font-size:18px;">package com.seven.spring.m_aop_helloworld;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class LogAdvice implements MethodInterceptor{


	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
		System.out.println("==开始执行操作==");
		Object res = methodInvocation.proceed();//执行原方法
		System.out.println("==操作结束==");
		return res;
	}
}
</span>

四、测试类MainTest,在测试类中拦截了save和delete相关的方法,query相关的方法没有被拦截

<span style="font-size:18px;">package com.seven.spring.m_aop_helloworld;

import org.junit.Test;
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.NameMatchMethodPointcut;
/**
 * 使用编程方式实现aop
 * @author Administrator
 *
 */
public class MainTest {
	
	@Test
	public void test1(){
		
		UserService userService = new UserServiceImpl();
		
		//1.声明切入点,表示要拦截哪些方法
		NameMatchMethodPointcut pointcut = new NameMatchMethodPointcut();
		pointcut.addMethodName("save*");
		pointcut.addMethodName("delete*");
		
		//2.声明一个通知,表示拦截到之后要做什么事
		LogAdvice logAdvice = new LogAdvice();
		
		//3.组装一个切面(切面=切入点+通知)
		Advisor advisor = new DefaultPointcutAdvisor(pointcut, logAdvice);
		
		//4.为原对象生成一个代理对象
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.addAdvisor(advisor);//添加一个切面
		proxyFactory.setTarget(userService);//指定目标对象0 
		userService = (UserService) proxyFactory.getProxy();//得到一个代理对象
		
		//=========================
		//使用的是代理对象
		userService.saveUser();
		System.out.println("--------------");
		
		userService.queryUsers();
		System.out.println("--------------");
		
		userService.deleteUser();
	}
}
</span>




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值