iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >spring boot 动态生成接口实现类的场景分析
  • 430
分享到

spring boot 动态生成接口实现类的场景分析

2024-04-02 19:04:59 430人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

目录一:定义注解二:建立动态代理类三:注入spring容器四:编写拦截器五:新建测试类在某些业务场景中,我们只需要业务代码中定义相应的接口或者相应的注解,并不需要实现对应的逻辑。 比

在某些业务场景中,我们只需要业务代码中定义相应的接口或者相应的注解,并不需要实现对应的逻辑。

比如 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 {
		
		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);

}

项目结构:

到此这篇关于Spring Boot 动态生成接口实现类的文章就介绍到这了,更多相关spring boot 接口实现类内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: spring boot 动态生成接口实现类的场景分析

本文链接: https://www.lsjlt.com/news/158708.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作