标签:springboot 代码 springframework proxy cglib org import tServiceInfo
cglib动态代理demo
通过动态代理实现方法拦截,可以:
- 返回特定值;
- 实现特定逻辑;
- 前后逻辑增强;
import cn.cloudwalk.entity.TServiceInfo;
import cn.cloudwalk.service.TServiceInfoService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.List;
/**
* (TServiceInfo)表控制层
*
* @author makejava
* @since 2021-02-02 15:34:01
*/
@RestController
@RequestMapping("tServiceInfo")
public class TServiceInfoController {
/**
* 服务对象
*/
@Resource
private TServiceInfoService tServiceInfoService;
/**
* 通过主键查询单条数据
*
* @param id 主键
* @return 单条数据
*/
@GetMapping("selectOne")
public TServiceInfo selectOne(Integer id) {
//使用cglib增强器创建代理类对象
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.tServiceInfoService.getClass());
enhancer.setCallback(new MyProxy());
TServiceInfoService proxy = (TServiceInfoService) enhancer.create();
//使用代理类对象调用方法
TServiceInfo tServiceInfo = proxy.queryById(id);
System.out.println("代理类调用被拦截的方法:"+ JSONObject.toJSONString(tServiceInfo));
List<TServiceInfo> tServiceInfos = proxy.queryAllByLimit(0, 10);
System.out.println("代理类调用其他方法:"+tServiceInfos);
return this.tServiceInfoService.queryById(id);
}
/**
* 方法拦截器,配合cglib代理使用
*/
private static class MyProxy implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
if (!(obj instanceof TServiceInfoService)) {
//调用者不是预想的,放行
return methodProxy.invokeSuper(obj, objects);
}
if ("queryById".equals(methodProxy.getSignature().getName())) {
//拦截这个方法,并返回结果给调用者
System.out.println("拦截到了");
TServiceInfo tServiceInfo = new TServiceInfo();
tServiceInfo.setServiceName("demo");
tServiceInfo.setId(234);
//直接返回结果给调用者
return tServiceInfo;
}
//放行前后逻辑
System.out.println("Before:" + methodProxy.getSignature().getName());
//放行
Object o = methodProxy.invokeSuper(obj, objects);
System.out.println("After:" + methodProxy.getSignature().getName());
return o;
}
}
}
标签:springboot,代码,springframework,proxy,cglib,org,import,tServiceInfo 来源: https://blog.csdn.net/A434534658/article/details/113618309
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。