Spring中最常用的11个扩展点

之前给大家写过一篇 bean 的生命周期,非常受欢迎,里面其实介绍了 bean 生命周期中所有的扩展点。
今天给大家带来的文章,可以作为 spring 扩展点的补充,一共 11 个,工作中会经常用到,如果用得好,很可能会事半功倍哈。
前言 我们一说到spring,可能第一个想到的是 ioc(控制反转) 和 aop(面向切面编程)。
没错,它们是spring的基石,得益于它们的优秀设计,使得spring能够从众多优秀框架中脱颖而出。
除此之外,我们在使用spring的过程中,有没有发现它的扩展能力非常强。由于这个优势的存在,让spring拥有强大的包容能力,让很多第三方应用能够轻松投入spring的怀抱。比如:rocketmq、mybatis、redis等。
今天跟大家一起聊聊,在spring中最常用的11个扩展点。
基于 spring boot + mybatis plus + vue & element 实现的后台管理系统 + 用户小程序,支持 rbac 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能
项目地址:https://github.com/yunaiv/ruoyi-vue-pro 视频教程:https://doc.iocoder.cn/video/ 1.自定义拦截器 spring mvc拦截器根spring拦截器相比,它里面能够获取httpservletrequest和httpservletresponse等web对象实例。
spring mvc拦截器的顶层接口是:handlerinterceptor,包含三个方法:
prehandle 目标方法执行前执行 posthandle 目标方法执行后执行 aftercompletion 请求完成时执行 为了方便我们一般情况会用handlerinterceptor接口的实现类handlerinterceptoradapter类。
假如有权限认证、日志、统计的场景,可以使用该拦截器。
第一步,继承handlerinterceptoradapter类定义拦截器:
public class authinterceptor extends handlerinterceptoradapter {    @override    public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler)            throws exception {        string requesturl = request.getrequesturi();        if (checkauth(requesturl)) {            return true;        }        return false;    }    private boolean checkauth(string requesturl) {        system.out.println(===权限校验===);        return true;    }} 第二步,将该拦截器注册到spring容器:
@configurationpublic class webauthconfig extends webmvcconfigureradapter {     @bean    public authinterceptor getauthinterceptor() {        return new authinterceptor();    }    @override    public void addinterceptors(interceptorregistry registry) {        registry.addinterceptor(new authinterceptor());    }} 第三步,在请求接口时spring mvc通过该拦截器,能够自动拦截该接口,并且校验权限。
基于 spring cloud alibaba + gateway + nacos + rocketmq + vue & element 实现的后台管理系统 + 用户小程序,支持 rbac 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能
项目地址:https://github.com/yunaiv/yudao-cloud 视频教程:https://doc.iocoder.cn/video/ 2.获取spring容器对象 在我们日常开发中,经常需要从spring容器中获取bean,但你知道如何获取spring容器对象吗?
2.1 beanfactoryaware接口 @servicepublic class personservice implements beanfactoryaware {    private beanfactory beanfactory;    @override    public void setbeanfactory(beanfactory beanfactory) throws beansexception {        this.beanfactory = beanfactory;    }    public void add() {        person person = (person) beanfactory.getbean(person);    }} 实现beanfactoryaware接口,然后重写setbeanfactory方法,就能从该方法中获取到spring容器对象。
2.2 applicationcontextaware接口 @servicepublic class personservice2 implements applicationcontextaware {    private applicationcontext applicationcontext;    @override    public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception {        this.applicationcontext = applicationcontext;    }    public void add() {        person person = (person) applicationcontext.getbean(person);    }} 实现applicationcontextaware接口,然后重写setapplicationcontext方法,也能从该方法中获取到spring容器对象。
2.3 applicationlistener接口 @servicepublic class personservice3 implements applicationlistener {    private applicationcontext applicationcontext;    @override    public void onapplicationevent(contextrefreshedevent event) {        applicationcontext = event.getapplicationcontext();    }    public void add() {        person person = (person) applicationcontext.getbean(person);    }} 3.全局异常处理 以前我们在开发接口时,如果出现异常,为了给用户一个更友好的提示,例如:
@requestmapping(/test)@restcontrollerpublic class testcontroller {    @getmapping(/add)    public string add() {        int a = 10 / 0;        return 成功;    }} 如果不做任何处理请求add接口结果直接报错:
what?用户能直接看到错误信息?
这种交互方式给用户的体验非常差,为了解决这个问题,我们通常会在接口中捕获异常:
@getmapping(/add)public string add() {    string result = 成功;    try {        int a = 10 / 0;    } catch (exception e) {        result = 数据异常;    }    return result;} 接口改造后,出现异常时会提示:“数据异常”,对用户来说更友好。
看起来挺不错的,但是有问题。。。
如果只是一个接口还好,但是如果项目中有成百上千个接口,都要加上异常捕获代码吗?
答案是否定的,这时全局异常处理就派上用场了:restcontrolleradvice。
@restcontrolleradvicepublic class globalexceptionhandler {    @exceptionhandler(exception.class)    public string handleexception(exception e) {        if (e instanceof arithmeticexception) {            return 数据异常;        }        if (e instanceof exception) {            return 服务器内部异常;        }        retur nnull;    }} 只需在handleexception方法中处理异常情况,业务接口中可以放心使用,不再需要捕获异常(有人统一处理了)。真是爽歪歪。
4.类型转换器 spring目前支持3中类型转换器:
converter:将 s 类型对象转为 t 类型对象 converterfactory:将 s 类型对象转为 r 类型及子类对象 genericconverter:它支持多个source和目标类型的转化,同时还提供了source和目标类型的上下文,这个上下文能让你实现基于属性上的注解或信息来进行类型转换。 这3种类型转换器使用的场景不一样,我们以converter为例。假如:接口中接收参数的实体对象中,有个字段的类型是date,但是实际传参的是字符串类型:2021-01-03 1015,要如何处理呢?
第一步,定义一个实体user:
@datapublic class user {    private long id;    private string name;    private date registerdate;} 第二步,实现converter接口:
public class dateconverter implements converter {    private simpledateformat simpledateformat = new simpledateformat(yyyy-mm-dd hhss);    @override    public date convert(string source) {        if (source != null && !.equals(source)) {            try {                simpledateformat.parse(source);            } catch (parseexception e) {                e.printstacktrace();            }        }        return null;    }} 第三步,将新定义的类型转换器注入到spring容器中:
@configurationpublic class webconfig extends webmvcconfigureradapter {    @override    public void addformatters(formatterregistry registry) {        registry.addconverter(new dateconverter());    }} 第四步,调用接口
@requestmapping(/user)@restcontrollerpublic class usercontroller {    @requestmapping(/save)    public string save(@requestbody user user) {        return success;    }} 请求接口时user对象中registerdate字段会被自动转换成date类型。
5.导入配置 有时我们需要在某个配置类中引入另外一些类,被引入的类也加到spring容器中。这时可以使用@import注解完成这个功能。
如果你看过它的源码会发现,引入的类支持三种不同类型。
但是我认为最好将普通类和@configuration注解的配置类分开讲解,所以列了四种不同类型:
5.1 普通类 这种引入方式是最简单的,被引入的类会被实例化bean对象。
public class a {}@import(a.class)@configurationpublic class testconfiguration {} 通过@import注解引入a类,spring就能自动实例化a对象,然后在需要使用的地方通过@autowired注解注入即可:
@autowiredprivate a a; 是不是挺让人意外的?不用加@bean注解也能实例化bean。
5.2 配置类 这种引入方式是最复杂的,因为@configuration注解还支持多种组合注解,比如:
@import @importresource @propertysource等。 public class a {}public class b {}@import(b.class)@configurationpublic class aconfiguration {    @bean    public a a() {        return new a();    }}@import(aconfiguration.class)@configurationpublic class testconfiguration {} 通过@import注解引入@configuration注解的配置类,会把该配置类相关@import、@importresource、@propertysource等注解引入的类进行递归,一次性全部引入。
5.3 importselector 这种引入方式需要实现importselector接口:
public class aimportselector implements importselector {private static final string class_name = com.sue.cache.service.test13.a;     public string[] selectimports(annotationmetadata importingclassmetadata) {        return new string[]{class_name};    }}@import(aimportselector.class)@configurationpublic class testconfiguration {} 这种方式的好处是selectimports方法返回的是数组,意味着可以同时引入多个类,还是非常方便的。
5.4 importbeandefinitionregistrar 这种引入方式需要实现importbeandefinitionregistrar接口:
public class aimportbeandefinitionregistrar implements importbeandefinitionregistrar {    @override    public void registerbeandefinitions(annotationmetadata importingclassmetadata, beandefinitionregistry registry) {        rootbeandefinition rootbeandefinition = new rootbeandefinition(a.class);        registry.registerbeandefinition(a, rootbeandefinition);    }}@import(aimportbeandefinitionregistrar.class)@configurationpublic class testconfiguration {} 这种方式是最灵活的,能在registerbeandefinitions方法中获取到beandefinitionregistry容器注册对象,可以手动控制beandefinition的创建和注册。
6.项目启动时 有时候我们需要在项目启动时定制化一些附加功能,比如:加载一些系统参数、完成初始化、预热本地缓存等,该怎么办呢?
好消息是springboot提供了:
commandlinerunner applicationrunner 这两个接口帮助我们实现以上需求。
它们的用法还是挺简单的,以applicationrunner接口为例:
@componentpublic class testrunner implements applicationrunner {    @autowired    private loaddataservice loaddataservice;    public void run(applicationarguments args) throws exception {        loaddataservice.load();    }} 实现applicationrunner接口,重写run方法,在该方法中实现自己定制化需求。
如果项目中有多个类实现了applicationrunner接口,他们的执行顺序要怎么指定呢?
答案是使用@order(n)注解,n的值越小越先执行。当然也可以通过@priority注解指定顺序。
7.修改beandefinition spring ioc在实例化bean对象之前,需要先读取bean的相关属性,保存到beandefinition对象中,然后通过beandefinition对象,实例化bean对象。
如果想修改beandefinition对象中的属性,该怎么办呢?
答:我们可以实现beanfactorypostprocessor接口。
@componentpublic class mybeanfactorypostprocessor implements beanfactorypostprocessor {        @override    public void postprocessbeanfactory(configurablelistablebeanfactory configurablelistablebeanfactory) throws beansexception {        defaultlistablebeanfactory defaultlistablebeanfactory = (defaultlistablebeanfactory) configurablelistablebeanfactory;        beandefinitionbuilder beandefinitionbuilder = beandefinitionbuilder.genericbeandefinition(user.class);        beandefinitionbuilder.addpropertyvalue(id, 123);        beandefinitionbuilder.addpropertyvalue(name, 苏三说技术);        defaultlistablebeanfactory.registerbeandefinition(user, beandefinitionbuilder.getbeandefinition());    }} 在postprocessbeanfactory方法中,可以获取beandefinition的相关对象,并且修改该对象的属性。
8.初始化bean前后 有时,你想在初始化bean前后,实现一些自己的逻辑。
这时可以实现:beanpostprocessor接口。
该接口目前有两个方法:
postprocessbeforeinitialization 该在初始化方法之前调用。 postprocessafterinitialization 该方法再初始化方法之后调用。 例如:
@componentpublic class mybeanpostprocessor implements beanpostprocessor {    @override    public object postprocessafterinitialization(object bean, string beanname) throws beansexception {        if (bean instanceof user) {            ((user) bean).setusername(苏三说技术);        }        return bean;    }} 如果spring中存在user对象,则将它的username设置成:苏三说技术。
其实,我们经常使用的注解,比如:@autowired、@value、@resource、@postconstruct等,是通过autowiredannotationbeanpostprocessor和commonannotationbeanpostprocessor实现的。
9.初始化方法 目前spring中使用比较多的初始化bean的方法有:
使用@postconstruct注解 实现initializingbean接口 9.1 使用@postconstruct注解 @servicepublic class aservice {    @postconstruct    public void init() {        system.out.println(===初始化===);    }} 在需要初始化的方法上增加@postconstruct注解,这样就有初始化的能力。
9.2 实现initializingbean接口 @servicepublic class bservice implements initializingbean {    @override    public void afterpropertiesset() throws exception {        system.out.println(===初始化===);    }} 实现initializingbean接口,重写afterpropertiesset方法,该方法中可以完成初始化功能。
10.关闭容器前 有时候,我们需要在关闭spring容器前,做一些额外的工作,比如:关闭资源文件等。
这时可以实现disposablebean接口,并且重写它的destroy方法:
@servicepublic class dservice implements initializingbean, disposablebean {     @override    public void destroy() throws exception {        system.out.println(disposablebean destroy);    }     @override    public void afterpropertiesset() throws exception {        system.out.println(initializingbean afterpropertiesset);    }} 这样spring容器销毁前,会调用该destroy方法,做一些额外的工作。
通常情况下,我们会同时实现initializingbean和disposablebean接口,重写初始化方法和销毁方法。
11.自定义作用域 我们都知道spring默认支持的scope只有两种:
singleton 单例,每次从spring容器中获取到的bean都是同一个对象。 prototype 多例,每次从spring容器中获取到的bean都是不同的对象。 spring web又对scope进行了扩展,增加了:
requestscope 同一次请求从spring容器中获取到的bean都是同一个对象。 sessionscope 同一个会话从spring容器中获取到的bean都是同一个对象。 即便如此,有些场景还是无法满足我们的要求。
比如,我们想在同一个线程中从spring容器获取到的bean都是同一个对象,该怎么办?
这就需要自定义scope了。
第一步实现scope接口:
public class threadlocalscope implements scope {    private static final threadlocal thread_local_scope = new threadlocal();    @override    public object get(string name, objectfactory objectfactory) {        object value = thread_local_scope.get();        if (value != null) {            return value;        }        object object = objectfactory.getobject();        thread_local_scope.set(object);        return object;    }    @override    public object remove(string name) {        thread_local_scope.remove();        return null;    }    @override    public void registerdestructioncallback(string name, runnable callback) {    }    @override    public object resolvecontextualobject(string key) {        return null;    }    @override    public string getconversationid() {        return null;    }} 第二步将新定义的scope注入到spring容器中:
@componentpublic class threadlocalbeanfactorypostprocessor implements beanfactorypostprocessor {    @override    public void postprocessbeanfactory(configurablelistablebeanfactory beanfactory) throws beansexception {        beanfactory.registerscope(threadlocalscope, new threadlocalscope());    }} 第三步使用新定义的scope:
@scope(threadlocalscope)@servicepublic class cservice {    public void add() {    }}


TDA2030功放电路单电源电路
现实情况!苹果的AR人工智能比谷歌的更智能更接近现实!
智慧灯杆在浙江绍兴柯桥市政道路中的应用案例
华为与中国交通建设公司部署连接柬埔寨和香港的海底电缆
鱼眼镜头的简介及用途
Spring中最常用的11个扩展点
什么是CGI?CGI程序小例子介绍
数值模拟在主动跟踪激光3D打印熔池的凝固行为
主打一个“和而不同”,哪吒X的“机甲风”美得很高级
iQOO Pro 5G版搭载骁龙855 Plus移动平台安兔兔跑分接近50万分
DTOS帝拓思3D引擎将帮助实现国产化替代
环保局CEMS数采仪
Apple Watch Series 7再次升级换代
短波超再生式接收机,Shortwave radio
电网谐波的概念、来源及抑制方法
电池修复,电瓶安装的位置对寿命使用有影响吗?
王兴的互联网“赌局”将迎来终局?
RTL8380M管理型交换机系统软件操作指南一:端口配置
设计低静态电流汽车电池反向保护系统的3种方法
典型的二次原理图