如何利用Spring的@Import扩展点与spring进行无缝整合
利用spring的@import扩展与spring进行无缝整合前言beanfactorypostprocessor@import实现pom文件定义数据层resource(dao)层的扫描注解定义我的数据层resource使用的注解arteryresourceimportbeandefinitionregistrar实现自定义扫描类classpatharteryresourcescanner代理注册工厂resourceregistryresouce的代理工厂真正的代理类方法调用类abstractbeandefinitionfactory我们编写测试,来启动我们的spring容器类图
前言
spring有那些扩展呢?
spring的扩展非常多,比较常用的就是
beanfactorypostprocessor 我们可以插手spring bean工厂的初始化
beanpostprocessor 我们可以插手spring bean实例化前后(比如spring aop)
@import
importaware。
beanfactorypostprocessor
spring的扩展点之一beanfactorypostprocessor,这个学名叫spring的bean工厂后置处理器,
它可以插手spring bean工厂的实例化,我们可以启动spring的时候自己手动注册一个bean工厂后置处理器,它能做的事情太多,研究过spring源码的同学都知道,spring容器启动时候,会先暴露一个工厂出来,这个工厂就是defaultlistablebeanfactory,这里面放置了我们的beandeinition,我们都知道spring 单例bean容器放了很多单例的bean,而这些bean最后都是来自于defaultlistablebeanfactory中的bd容器;
beanfactorypostprocessor是spring提供给我们来扩展spring的,当然了它自己也在用,spring有自己内部的bean工厂后置处理器,处理的时候讲我们的和spring自己的一起处理。我们只需要把我们新建的类实现了beanfactorypostprocessor,并且加入@component或者交给@import就可以了。实现这个接口必须实现它的一个方法,它的这个方法就可以得到我们的beandefinittionmap,也就是bdmap,这里面放置了我们系统所有的注册到spring容器里面的bd,最后spring循环这个bd,将其实例化成对象放入bean容器。
今天我们的主题是使用sprinng的扩展点之一的@import来实现公司的平台与spring整合,类似于mybatis与spring整合一样
@import
这个要说就要说很久,如果没有研究过spring底层源码的,可以去研究下,功能非常强大这边我大概介绍一下:
@import支持3中类型:
普通类(spring管理的类):就是讲一个普通的类通过@import导入,而不适用@component,但是这样做毫无意义。
实现了importselector:实现这个接口要求实现它的一个方法返回一个类名列表
registrar:真正牛逼的注册类,实现了它,我们可以手动往里面添加自己的beandefiniton,自己实现扫描机制,自己实现很多很多自己的逻辑(mybatis整合spring就用的它)
实现
我的工程命名是:xxx-spring-platform-1.0.realse
xxx是公司的简称
工程结构:
其中context是核心,core是一些常用的核心类,aop写了一半,还没完成
pom文件
<dependency> <groupid>org.springframework</groupid> <artifactid>spring-core</artifactid> <version>5.2.7.release</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-context</artifactid> <version>5.2.7.release</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-beans</artifactid> <version>5.2.7.release</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-aop</artifactid> <version>5.2.7.release</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-context-support</artifactid> <version>5.2.7.release</version> </dependency>
就是用了srping的几个基础包
定义数据层resource(dao)层的扫描注解
@documented @retention(runtime) @target(type) @import(arteryresourceimportbeandefinitionregistrar.class) //这个是用了spring的@import //其中用了其扩展点之一的@import中的registrar,arteryresourceimportbeandefinitionregistrar才是我们的核心所在 public @interface arteryresourcescan { string[] value() default {}; /** * 基础包模式 */ string[] basepackages() default {}; /** * 通配符的模式 */ string[] typealiases() default {}; /** * artery resource工厂bean * * @return */ class<? extends arteryresourcefactorybean> factorybean() default arteryresourcefactorybean.class; /** * this property specifies the annotation that the scanner will search for. * <p> * the scanner will register all interfaces in the base package that also have * the specified annotation * </p> */ class<? extends annotation> annotationclass() default annotation.class; /** * this property specifies the parent that the scanner will search for. * <p> * the scanner will register all interfaces in the base package that also have * the specified interface class as a parent. * </p> */ class<?> markerinterface() default class.class; /** * the property specifies the beanname gererator will extends parent */ class<? extends beannamegenerator> namegenerator() default beannamegenerator.class; /** * is lazy load,default false */ boolean lazy() default false; /** * scope default singleton */ string scope() default abstractbeandefinition.scope_singleton; }
定义我的数据层resource使用的注解
arteryresourceimportbeandefinitionregistrar实现
我们的注册类实现了spring的即可importbeandefinitionregistrar,而importbeandefinitionregistrar提供了一个方法registerbeandefinitions可以得到我们的arteryresourcescan 注解,从而定义自己的扫描规则,使用spring的的扫描逻辑帮助我们完成扫描,然后注册到bdmap里面,因我们的resource层是接口,而spring实例化是不能实例化接口的,所以当spring帮我们扫描成bd的时候,我们这个时候要这个扫描的列表取出来,替换我们的接口类,怎么替换呢?
因为接口需要被代理出去,而代理类帮我们完成我们想要做的事情,比如数据查询,所以我们还需要定义一个工厂bean即factorybean,它来帮我们产生对象,factorybean也是一个bean,但是他比较特殊,它可以产生对象,我们先看registrar的实现:
public class arteryresourceimportbeandefinitionregistrar implements importbeandefinitionregistrar { private final string default_resourace_pattern = "**/*.class"; @override public void registerbeandefinitions(annotationmetadata importingclassmetadata, beandefinitionregistry registry) { classpatharteryresourcescanner scanner = new classpatharteryresourcescanner(registry); /** * 拿到注解信息 */ annotationattributes annoattrs = annotationattributes.frommap(importingclassmetadata.getannotationattributes(arteryresourcescan.class.getname())); class<? extends arteryresourcefactorybean> factorybean = annoattrs.getclass("factorybean"); if (!arteryresourcefactorybean.class.equals(factorybean)) { scanner.setarteryresourcefactorybean(beanutils.instantiateclass(factorybean)); } class<? extends annotation> annotionclass = annoattrs.getclass("annotationclass"); if (!annotation.class.equals(annotionclass)) { scanner.setannotationclass(annotionclass); } class<?> markerinteface = annoattrs.getclass("markerinterface"); if (!class.class.equals(markerinteface)) { scanner.setmarkerinterface(markerinteface); } class<? extends beannamegenerator> namegenerator = annoattrs.getclass("namegenerator"); if (!beannamegenerator.class.equals(namegenerator)) { scanner.setbeannamegenerator(beanutils.instantiateclass(namegenerator)); } scanner.setlazy(annoattrs.getboolean("lazy")); scanner.setresourcescope(annoattrs.getstring("scope")); //base package handler list<string> basepackages = new arraylist<>(20); arrays.aslist(annoattrs.getstringarray("basepackages")).foreach(item -> { if (stringutils.hastext(item)) { basepackages.add(item); } }); arrays.aslist(annoattrs.getstringarray("value")).foreach(item -> { if (stringutils.hastext(item)) { basepackages.add(item); } }); /** * 处理通配符的扫描问题 */ string[] typealis = annoattrs.getstringarray("typealiases"); if (typealis != null && typealis.length > 0) { resourcepatternresolver resolver = new pathmatchingresourcepatternresolver(); metadatareaderfactory metadatareaderfactory = new cachingmetadatareaderfactory(resolver); //typealiaes for (string typealiases : arrays.aslist(annoattrs.getstringarray("typealiases"))) { getresource(resolver, metadatareaderfactory, typealiases, basepackages); } } scanner.registerfilters(); scanner.doscan(stringutils.tostringarray(basepackages)); } private void getresource(resourcepatternresolver resolver, metadatareaderfactory metadatareaderfactory, string classpath, list<string> basepackages) { classpath = resourcepatternresolver.classpath_all_url_prefix + classutils.convertclassnametoresourcepath(classpath) + "/" + default_resourace_pattern; try { resource[] resources = resolver.getresources(classpath); if (resources != null && resources.length > 0) { metadatareader metadatareader = null; for (resource resource : resources) { if (resource.isreadable()) { metadatareader = metadatareaderfactory.getmetadatareader(resource); basepackages.add(class.forname(metadatareader.getclassmetadata().getclassname()).getpackage().getname()); } } } } catch (ioexception | classnotfoundexception e) { e.printstacktrace(); } } }
以上代码的doscan方法是核心,是调用了我们自定义的扫描类
自定义扫描类classpatharteryresourcescanner
public class classpatharteryresourcescanner extends classpathbeandefinitionscanner { private final logger logger = loggerfactory.getlogger(classpatharteryresourcescanner.class); /** * factory baen instance */ private arteryresourcefactorybean<?> arteryresourcefactorybean = new arteryresourcefactorybean<object>(); /** * scanner class */ private class<? extends annotation> annotationclass; /** * scanner class */ private class<?> markerinterface; /** * is lazy load ,default false */ private boolean islazy = false; /** * scope is cantains singleton and prototype,default singlton */ private string resourcescope = abstractbeandefinition.scope_singleton; /** * 调用父类的构造,构造出扫描对象 * * @param registry */ public classpatharteryresourcescanner(beandefinitionregistry registry) { super(registry, false); } public void registerfilters() { //是否允许所有的所有的接口(预留) boolean acceptallintefaces = true; if (this.annotationclass != null) { addincludefilter(new annotationtypefilter(this.annotationclass)); acceptallintefaces = false; } if (this.markerinterface != null) { addincludefilter(new assignabletypefilter(this.markerinterface)); acceptallintefaces = false; } if (acceptallintefaces) { addincludefilter(new typefilter() { @override public boolean match(metadatareader metadatareader, metadatareaderfactory metadatareaderfactory) throws ioexception { return true; } }); } } @override public set<beandefinitionholder> doscan(string... basepackages) { set<beandefinitionholder> beandefinitions = super.doscan(basepackages); if (!beandefinitions.isempty()) { //spring 扫描到每个加了@component或者@service 成bd processbeandefinitions(beandefinitions); } return beandefinitions; } private void processbeandefinitions(set<beandefinitionholder> beandefinitions) { beandefinitions.foreach(this::processbeandefinition); } private void processbeandefinition(beandefinitionholder holder) { genericbeandefinition definition = (genericbeandefinition) holder.getbeandefinition(); if (logger.isdebugenabled()) { logger.debug("creating arteryresourcebean with name {} and {} mapperinterfaces", holder.getbeanname(), definition.getbeanclassname()); } definition.getconstructorargumentvalues().addgenericargumentvalue(definition.getbeanclassname()); definition.setbeanclass(this.arteryresourcefactorybean.getclass()); definition.setlazyinit(islazy);//延迟加载 definition.setscope(resourcescope); definition.setautowiremode(abstractbeandefinition.autowire_by_type); } @override protected boolean checkcandidate(string beanname, beandefinition beandefinition) throws illegalstateexception { // check is sucess boolean issucc = true; if (super.checkcandidate(beanname, beandefinition)) { issucc = true; } else { issucc = false; } return issucc; } @override protected boolean iscandidatecomponent(annotatedbeandefinition beandefinition) { boolean iscomponent = false; string beanclassname = beandefinition.getmetadata().getclassname(); iscomponent = beanclassname.endswith("resource"); try { iscomponent = iscomponent ? class.forname(beandefinition.getmetadata().getclassname()).isannotationpresent(arterydao.class) : false; } catch (classnotfoundexception e) { e.printstacktrace(); } if (iscomponent) { iscomponent = beandefinition.getmetadata().isinterface() && beandefinition.getmetadata().isindependent(); } return iscomponent; } public void setarteryresourcefactorybean(arteryresourcefactorybean<?> arteryresourcefactorybean) { this.arteryresourcefactorybean = arteryresourcefactorybean; } public void setannotationclass(class<? extends annotation> annotationclass) { this.annotationclass = annotationclass; } public void setlazy(boolean lazy) { islazy = lazy; } public void setresourcescope(string resourcescope) { this.resourcescope = resourcescope; } public void setmarkerinterface(class<?> markerinterface) { this.markerinterface = markerinterface; } }
processbeandefinition这个方法里面就拿到spring给我们扫描返回的bd,我们循环这个bd
然后替换我们的resource接口,这里用的是一个factorybean
而这个工厂bean里面的getobject是返回了一个代理对象,具体看下面代码:
代理注册工厂resourceregistry
它的作用主要是来管理我们的注册工厂
resouce的代理工厂
它来管理我们的resouce工厂,从这个resource工厂中产生代理类,也就是我们的代理类都在代理工厂中产生,然后我们调用的时候是通过它来产生的一个proxy
真正的代理类
public class resourceproxy<t> implements invocationhandler, serializable { private static final long serialversionuid = 1l; private final logger logger = loggerfactory.getlogger(resourceproxy.class); private final class<t> resourceinterface; private final map<method, resourcemethod> cachemethod; public resourceproxy(class<t> resourceinterface, map<method, resourcemethod> cachemethod) { this.resourceinterface = resourceinterface; this.cachemethod = cachemethod; } @override public object invoke(object proxy, method method, object[] args) throws throwable { object result = null; /** * handler tostring method */ if (object.class.equals(method.getdeclaringclass())) { result = method.invoke(this, args); } else if (isdefaultmethod(method)) { result = invokedefaultmethod(proxy, method, args); } else { /** * user invoke handler */ if (logger.isdebugenabled()) { logger.debug("resourceproxy.invoke begin ...."); logger.debug("================================================"); logger.debug("invoke interface name={}", proxy.getclass().getinterfaces()[0].getname()); logger.debug("invoke method name={}", method.getname()); logger.debug("invoke method args={}", args); } resourcemethod resourcemethod = getcachemethod(method); result = resourcemethod.execute(args); if (logger.isdebugenabled()) { logger.debug("resourceproxy.invoke end ...."); logger.debug("================================================"); logger.debug("invoke method result={}", result); } } return result; } public resourcemethod getcachemethod(method method) { resourcemethod resourcemethod = cachemethod.get(method); if (resourcemethod == null) { resourcemethod = new resourcemethod(method, resourceinterface); cachemethod.put(method, resourcemethod); } return resourcemethod; } /** * invoke default method * * @param proxy proxy object * @param method proxy invoke method * @param args method args * @return * @throws throwable */ private object invokedefaultmethod(object proxy, method method, object[] args) throws throwable { final constructor<methodhandles.lookup> constructor = methodhandles.lookup.class.getdeclaredconstructor(class.class, int.class); if (!constructor.isaccessible()) { constructor.setaccessible(true); } final class<?> declaringclass = method.getdeclaringclass(); return constructor.newinstance(declaringclass, methodhandles.lookup.private) .unreflectspecial(method, declaringclass).bindto(proxy).invokewitharguments(args); } /** * check is default method * * @param method * @return */ private boolean isdefaultmethod(method method) { return ((method.getmodifiers() & (modifier.abstract | modifier.public | modifier.static)) == modifier.public) && method.getdeclaringclass().isinterface(); } }
方法调用类
public class resourcemethod<t> extends abstractannotaionhandlerresource<t> { private final method method; private final class<?> resourceinterface; public resourcemethod(method method, class<?> resourceinterface) { this.method = method; this.resourceinterface = resourceinterface; } public object execute(object[] args) throws exception { object result = null; inittemplate(); if (method.isannotationpresent(pubhandler.class)) { result = pubhandler(args); } else { result = invokeextmethod(args); } return result; } private void inittemplate(){ if(querytemplate == null){ querytemplate = springcontainerapplicationcontext.getinstance().getbean("querytemplate"); } if(updatetemplate == null){ updatetemplate =springcontainerapplicationcontext.getinstance().getbean("updatetemplate"); } } private object invokeextmethod(object[] args) throws exception { object result = null; annotation[] annotations = method.getannotations(); if (annotations != null && annotations.length > 0) { string annotationname = annotations[0].annotationtype().getsimplename(); sqlcommandtype type = sqlcommandtype.valueof(annotationname); switch (type) { case select: result = executequery(method.getannotation(select.class), args); break; case insert: result = executeinsert(method.getannotation(insert.class), args); break; case delete: result = executedelete(method.getannotation(delete.class), args); break; case update: result = executeupdate(method.getannotation(update.class), args); break; } } return result; } private object pubhandler(object[] args) { object result = null; pubhandler ph = method.getannotation(pubhandler.class); switch (ph.handlertype()) { case p_q_paging: result = p_q_paging(args); break; case l_q_paging: result = l_q_paging(args); break; case i_persistence_in: result = i_persistence_in(args); break; case i_persistence_up: result = i_persistence_up(args); break; case i_persistence_up_override: result = i_persistence_up_override(args); break; case i_psersistence_de: result = i_psersistence_de(args); break; case i_psersistence_de_override: result = i_psersistence_de_override(args); break; case e_q_get: result = e_q_get(args); break; case l_q_entity: result = l_q_entity(args); break; case l_q_entity_override: result = l_q_entity_override(args); break; case i_batch_persistence: result = i_batch_persistence(args); break; case i_count: result = i_count(args); break; } return result; } @override public method getmethod() { return method; } @override public class<?> targetinterface() { return resourceinterface; }
从第七步调用直接到了这里,其中1和2是不一样的,哪里不一样呢?因为pubhandler是我们在基类里面封装的curd操作,如果是调用基类,那么会直接将请求代理给我的基类去做,如果是通过注解sql的那么就执行invokeextmethod
最后我们编写一个工厂来获取我们的bean
abstractbeandefinitionfactory
public abstract class abstractbeandefinitionfactory extends annotationconfigdefinitionapplicationcontext implements beandefinitionfactory { @suppresswarnings("unchecked") @override public <k> k getbean(string beanname) { check(); definitionbeanfactory<k> beanfactory = () -> { object beaninstance = super.applicationcontxt.getbean(beanname); if (beaninstance != null) { return (k) beaninstance; } else { throw new runtimeexception(" get spring ioc instance is null "); } }; return beanfactory.getbeanobject(); } @override public <k> k getbean(class<k> kclzz) { check(); definitionbeanfactory<k> beanfactory = () -> super.applicationcontxt.getbean(kclzz); return beanfactory.getbeanobject(); } private void check() { if(!super.runstatus) { throw new runtimeexception("spring 容器未运行"); } } @override public <k> k getbean(string beanname, class<k> kclass) { check(); definitionbeanfactory<k> beanfactory = () -> super.applicationcontxt.getbean(beanname,kclass); return null; } }
我们编写测试,来启动我们的spring容器
以上我只是提供了一个spring扩展的思路,上面截图和代码都不全,因为涉及到公司机密性,我没有办法暴露太多东西在上面,所以有兴趣可以一起交流交流;整合spring的这个框架是我自己编写,没有任何人参与进来,所以我希望如果有这方面兴趣的朋友可以一起交流交流
类图
我的启动类的之间关系(全部是自己的类,不是spring的类):
代理工厂调用的调用的方法处理继承关系:
最后预祝我的两个小公主一直开心快乐,身体永远健康,爸爸永远爱你们。
到此这篇关于如何利用spring的@import扩展点与spring进行无缝整合的文章就介绍到这了,更多相关spring的@import扩展点与spring无缝整合内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!