spring boot 动态生成接口实现类的场景分析
作者:mysgk 发布时间:2022-12-14 05:09:33
标签:spring,boot,接口,实现类
在某些业务场景中,我们只需要业务代码中定义相应的接口或者相应的注解,并不需要实现对应的逻辑。
比如 mybatis和feign: 在 mybatis 中,我们只需要定义对应的mapper接口;在 feign 中,我们只需要定义对应业务系统中的接口即可。
那么在这种场景下,具体的业务逻辑时怎么执行的呢,其实原理都是 * 。
我们这里不具体介绍 * ,主要看一下它在springboot项目中的实际应用,下面我们模仿feign来实现一个调用三方接口的 httpclient。
一: 定义注解
package com.mysgk.blogdemo.annotation;
public @interface MyHttpClient {
}
二: 建立 * 类
package com.mysgk.blogdemo.proxy;
import org.springframework.beans.factory.FactoryBean;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class RibbonAopProxyFactory<T> implements FactoryBean<T>, InvocationHandler {
private Class<T> interfaceClass;
public Class<T> getInterfaceClass() {
return interfaceClass;
}
public void setInterfaceClass(Class<T> interfaceClass) {
this.interfaceClass = interfaceClass;
}
@Override
public T getObject() throws Exception {
return (T) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{interfaceClass}, this);
}
@Override
public Class<?> getObjectType() {
return interfaceClass;
}
@Override
public boolean isSingleton() {
return true;
}
/**
真正执行的方法
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return "invoke " + proxy.getClass().getName() + "." + method.getName() + " , do anything ..";
}
}
三: 注入spring容器
package com.mysgk.blogdemo.start;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import com.mysgk.blogdemo.annotation.MyHttpClient;
import com.mysgk.blogdemo.proxy.RibbonAopProxyFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Set;
@Component
public class ScanHttpClients implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware {
private final Logger logger = LoggerFactory.getLogger(ScanHttpClients.class);
private ApplicationContext ctx;
public void run(BeanDefinitionRegistry registry) {
Set<Class<?>> scanPackage = ClassUtil.scanPackageByAnnotation("com.mysgk", MyHttpClient.class);
for (Class<?> cls : scanPackage) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(cls);
GenericBeanDefinition definition = (GenericBeanDefinition) builder.getRawBeanDefinition();
definition.getPropertyValues().add("interfaceClass", definition.getBeanClassName());
definition.setBeanClass(RibbonAopProxyFactory.class);
definition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE);
String beanName = StrUtil.removePreAndLowerFirst(cls.getSimpleName(), 0) + "RibbonClient";
registry.registerBeanDefinition(beanName, definition);
}
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
run(registry);
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.ctx = ctx;
}
}
四: 编写 *
package com.mysgk.blogdemo.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
@Aspect
public class InterceptAnnotation {
@Autowired
private RestTemplate ribbonLoadBalanced;
@Pointcut("@annotation(com.mysgk.blogdemo.annotation.MyHttpClient)")
public void execute() {
}
@Around("execute()")
public Object interceptAnnotation(ProceedingJoinPoint joinPoint) throws Throwable {
/**
* 此处省略 获取 url, httpMethod, requestEntity, responseType 等参数的处理过程
*/
ResponseEntity<?> exchange = ribbonLoadBalanced.exchange("url", HttpMethod.GET, HttpEntity.EMPTY, Object.class);
return exchange.getBody();
}
}
五: 新建测试类
package com.mysgk.blogdemo.client;
import com.mysgk.blogdemo.annotation.MyHttpClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@MyHttpClient
public interface MyHttpClientTest {
@PostMapping(value = "test/t1")
Object test(String param);
}
项目结构:
来源:https://www.cnblogs.com/mysgk/p/15607900.html


猜你喜欢
- 一、自己封装URLConnection 连接请求类 public void downloadFile1() { try{ &nb
- 前言刚看到这个题目的朋友第一反应肯定是好奇,之后再细细思考下就会发现这个题目眼熟了。就算是同一个答案,如果提问的方式不同,往往会对回答造成干
- 表格是最常用的数据统计形式之一,在 swing 中 由
- 接着上篇文章,我们继续来学习 Java 中的字节流操作。装饰者缓冲流 BufferedInput/OutputStream装饰者流其实是基于
- 本文实例讲述了Android实现给TableLayou绘制边框的方法。分享给大家供大家参考,具体如下:效果如下:思路:使用share作为背景
- 一、前言二、案例需求1.编写login.html登录页面,username&password两个输入框2.使用Druid数据库连接池
- 相信大家都见到了微信图标颜色渐变的过程,是不是感觉很牛逼?不得不说微信团队确实是很厉害的团队,不管是从设计还是开发人员。今天我带大家来看看,
- 目录为什么要实现调用链跟踪?如何实现?第一步,看图、看场景,用户浏览器的一次请求行为所走的路径是什么样的第二步,实现。不想看代码可直接拉最后
- 对于本地图片我们可以通过selector来轻松的实现点击态。 但是在我们的项目中,一个关于对非本地图片的点击态实现还是难倒了不少人;因此专门
- 由于项目需要在NDK中使用网络开发,对于c语言网络开发来说,libcurl库是个很不错的选择,但android系统中并没有自带该库,所以就得
- 目录迭代器原理:什么是迭代器,使用迭代器的好处?迭代器怎么实现的?迭代器的陷阱?为什么会产生这样的错误?遍历map的四种方式迭代器原理:什么
- 阿里终面在线编程题,写出来与大家分享一下 有一个单向链表
- 本文介绍了Spring Boot 部署jar和war两种方式的区别,分享给大家,具体如下:1、 packaging的方式不同,一种设置成ja
- 废话不多说了,直接给大家贴代码了,具体代码如下所示:<?xml version="1.0" encoding=&q
- 前言我们在使用spring security的时候可以通过好几种方法获取用户信息, 但是今天这篇文章介绍的是一个笔者觉得最优雅的实现; 借鉴
- idea 很强大,但是初次安装默认的有很多设置并不是满足我们开发的需要。以前经常一安装就要捣鼓很久,为此吐血整理初次安装设置一、切换主题(配
- 概述 这是一个自定义色盘,根据点,直线和圆的几何学加上hsv颜色模型完成技术点几何:圆的标准方程式:(x-a)²
- 1.什么是mybatis动态sql看到动态,我们就应该想到,这是一个可以变化的sql语句MyBatis的动态SQL是基于OGNL表达式的,它
- 本文是项目中使用了websocket进行一些数据的推送,对比项目做了一个demo,ws的相关问题不做细数,仅做一下记录。此demo针对ws的
- goto在Java中是一个保留字,但在语言中并没有用到它;Java没有goto。但是,Java也能完成一些类似于跳转的操作,主要是依靠:标签