继承方式代理

一、UserService类

<span style="font-size:18px;">package com.seven.spring.l_proxy_3_cglib;
//类不能是final的,这样就不能生成子类
public class UserService{
    //protected方法可以生成代理
    protected void fool1(){
    	System.out.println("protected方法");
    }
    //默认方法不能生成代理,因为子类不能访问
    void fool2(){
    	System.out.println("默认的方法");
    	fool3();
    }
    //private方法不能生成代理
    private void fool3(){
    	System.out.println("private的方法");
    }
    //static方法不能生成代理,因为static是类共有的
    public static void fool4(){
    	System.out.println("static的方法");
    }
    //final方法不能生成代理,因为final不能被子类重写
    public final void fool5(){
    	System.out.println("static的方法");
    }
	public void queryUsers() {
		System.out.println("查询一个User");	
	}

	public void saveUser() {
		System.out.println("保存一个User");
		
	}

	public void deleteUser() {
		System.out.println("删除一个User");
		
	}
}
</span>

二、LogCglibproxy代理对象实现MethodInterceptor接口

<span style="font-size:18px;">package com.seven.spring.l_proxy_3_cglib;
import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
 * 继承方式代理
 * @author Administrator
 *
 */
public class LogCglibproxy implements MethodInterceptor{
	private Object target; //目标对象
	 
	public LogCglibproxy(Object target) {
		this.target = target;
	}
	
	/**
	 * 创建代理对象
	 * @return
	 */
    public Object createProxyInstance(){
       Enhancer enhancer = new Enhancer();
       enhancer.setSuperclass(target.getClass());//设置父类为目标对象
       enhancer.setCallback(this);//回调方法
       return enhancer.create();
    }
	

	@Override
	public Object intercept(Object obj, Method method, Object[] args,
			MethodProxy proxy) throws Throwable {
		System.out.println("==开始执行操作==");
		Object res =method.invoke(target, args);//执行原方法
		System.out.println("==操作结束==");
		return res;
	}

}
</span>
三、测试类MainTest

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

import org.junit.Test;

public class MainTest {
	@Test
	public void test1(){
		
		UserService userService = new UserService();
		
		userService = (UserService) new LogCglibproxy(userService).createProxyInstance();//使用了包装之后的代理对象
		
		userService.saveUser();
		System.out.println("--------------");
		
		userService.queryUsers();
		System.out.println("--------------");
		
		userService.deleteUser();
		System.out.println("--------------");
		
		userService.fool1();
		System.out.println("--------------");
		userService.fool2();
		System.out.println("--------------");

		
	}

}</span>



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值