想减少代码量,快设置一个有感知的 Aware Spring Bean
摘要:正常情况下,Spring 中的 Bean 对 Spring 是无感知的,Spring 框架提供了这种扩展能力,能让一个 bean 成为有感知的。
本文分享自华为云社区《有感知的 Aware Spring Bean》,作者:陈皮的JavaLib。
有感知能力的 Spring Bean
正常情况下,Spring 中的 Bean 对 Spring 是无感知的,即它感知不到自己是由哪个 Bean 工厂(BeanFactory)创建的;感知不到自己在工厂中的 id,即 beanName;也感知不到 Spring 应用上下文对象(ApplicationContext)等等。
如果要想 Spring Bean 能感知到这些信息,我们可以自己通过某些手段来获取这些信息,然后设置到 bean 实例中。这种方法缺点是需要我们自己获取需要感知的信息,然后主动设置到 bean 中,会写许多冗余代码。但是优点是可以和 Spring 解耦。
当然,Spring 框架提供了这种扩展能力,能让一个 bean 成为有感知的。只要让 bean 类实现特定的接口,重写其中的方法即可。这样 Spring 会在 bean 的生命周期的某个阶段调用这些重写的方法,注入需要感知的信息。这方式的缺点是需要和 Spring 耦合,优点是能减少代码量,简单。
Aware 接口
要让 Spring 中的 bean 获得某些感知能力,需要实现特定的接口,这些接口有个共同的父接口,即 Aware 接口。
package org.springframework.beans.factory;
public interface Aware {
}
Aware 是一个标记接口,表明一个 bean 可以通过回调方法得到 Spring 容器中特定的对象。具体的方法签名由各个子接口定义,但通常应该只包含一个接受单个参数并返回 void 的方法。
注意,仅实现 Aware 接口不会提供默认功能。我们一般是实现 Aware 的子接口来获得特定的感知能力。
Aware 接口的子接口有很多,例如 BeanNameAware,BeanFactoryAware,ApplicationContextAware,EnvironmentAware,ApplicationEventPublisherAware 等等,以下介绍几个常用的用法。
BeanNameAware 接口
如果 bean 需要知道自己在 bean 工厂中的 beanName,即在 Spring 容器中的名字(标识)。可以实现此 BeanNameAware 接口。BeanNameAware 接口源码如下,只有一个方法,beanName 会通过这个方法设置到 bean 中。
package org.springframework.beans.factory;
public interface BeanNameAware extends Aware {
void setBeanName(String name);
}
其实,我们使用的 bean 一般不需要知道它在 beanFactory 中的名字,意义不大。一般是官方在 Spring 自身框架使用比较多,官方也不推荐我们使用,因为这样会导致 bean 依赖 Spring API。
package com.chenpi; import org.springframework.beans.factory.BeanNameAware;
import org.springframework.stereotype.Component; /**
* @author 陈皮
* @version 1.0
* @description
* @date 2022/4/3
*/
@Component
public class Person implements BeanNameAware { private String beanName; @Override
public void setBeanName(String name) {
this.beanName = name;
} public String getBeanName() {
return beanName;
}
}
编写测试单元,验证如下:
package com.chenpi; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest
class ApplicationTests { @Autowired
private Person person; @Test
public void testValue() {
System.out.println("Person BeanName:" + person.getBeanName());
} } // 输出结果如下
Person BeanName:person
BeanFactoryAware 接口
如果 Bean 想感知配置自己的 BeanFactory 对象,可以实现 BeanFactoryAware 接口。如果需要,bean 可以通过 BeanFactory 对象获取其他 bean 对象,进行协作。当然也不推荐这种方式,推荐使用 DI 方式注入依赖的 bean 对象。BeanFactoryAware 接口源码如下:
package org.springframework.beans.factory;
import org.springframework.beans.BeansException;
public interface BeanFactoryAware extends Aware {
// 在bean属性填充之后,但是在初始回调(例如afterPropertiesSet()方法)之前回调此方法
void setBeanFactory(BeanFactory beanFactory) throws BeansException;
}
测试代码以及单元测试验证结果如下:
package com.chenpi; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.stereotype.Component; /**
* @author 陈皮
* @version 1.0
* @description
* @date 2022/4/3
*/
@Component
public class Person implements BeanNameAware, BeanFactoryAware { private String beanName;
private BeanFactory beanFactory; @Override
public void setBeanName(String name) {
this.beanName = name;
} @Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
} public String getBeanName() {
return beanName;
} public BeanFactory getBeanFactory() {
return beanFactory;
}
}
package com.chenpi; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest
class ApplicationTests { @Autowired
private Person person; @Test
public void testValue() {
System.out.println("Person BeanName:" + person.getBeanName());
System.out.println("Person Bean's BeanFactory:" + person.getBeanFactory().getClass());
System.out.println(
person == person.getBeanFactory().getBean(person.getBeanName(), Person.class));
} } // 输出结果如下
Person BeanName:person
Person Bean's BeanFactory:class org.springframework.beans.factory.support.DefaultListableBeanFactory
true
ApplicationContextAware 接口
如果 Spring Bean 需要感知 Spring 容器,即 ApplicationContext 对象,可以实现 ApplicationContextAware 接口。可以通过 Spring 容器获取其他 Bean 对象,进行协作。
当然,如果一个 bean 对象需要访问文件资源,例如调用applicationContext.getResource()方法,或想要发布一个应用程序事件applicationContext.publishEvent(ApplicationEvent event),或需要访问MessageSource,此种方式可以实现。不过,官方对于这些的特定场景,最好实现更具体的ResourceLoaderAware、ApplicationEventPublisherAware或MessageSourceAware接口更合适。
package org.springframework.context; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.Aware; public interface ApplicationContextAware extends Aware { void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
测试代码以及单元测试验证结果如下:
package com.chenpi; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; /**
* @author 陈皮
* @version 1.0
* @description
* @date 2022/4/3
*/
@Component
public class Person implements BeanNameAware, BeanFactoryAware, ApplicationContextAware { private String beanName;
private BeanFactory beanFactory;
private ApplicationContext applicationContext; @Override
public void setBeanName(String name) {
this.beanName = name;
} @Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
} @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
} public String getBeanName() {
return beanName;
} public BeanFactory getBeanFactory() {
return beanFactory;
} public ApplicationContext getApplicationContext() {
return applicationContext;
}
}
package com.chenpi; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext; @SpringBootTest
class ApplicationTests { @Autowired
private Person person; @Test
public void testValue() {
System.out.println("Person BeanName:" + person.getBeanName());
System.out.println("Person Bean's BeanFactory:" + person.getBeanFactory().getClass());
System.out.println(
person == person.getBeanFactory().getBean(person.getBeanName(), Person.class));
ApplicationContext applicationContext = person.getApplicationContext();
Person person1 = applicationContext.getBean(person.getBeanName(), Person.class);
System.out.println(applicationContext.getClass());
System.out.println(person == person1);
} } // 输出结果如下
Person BeanName:person
Person Bean's BeanFactory:class org.springframework.beans.factory.support.DefaultListableBeanFactory
true
class org.springframework.web.context.support.GenericWebApplicationContext
true
想减少代码量,快设置一个有感知的 Aware Spring Bean的更多相关文章
- 前端程序员的蜕变——JS的 event 对象属性、使用实例、兼容性处理(极大提高代码效率、减少代码量)
下面讨论一下 js 中的 Event 对象,主要从以下三个方面详细的描述(点击标题可跳转到对应部分): 1.什么是event 2.怎么用event,用他该注意什么,几个简单实际应用 3.event在不 ...
- WPF INotifyPropertyChanged 通过特性减少代码量
在很多地方需要用上INotifyPropertyChanged的接口,MVVM模式,List等集合都会用到. 通常我们使用 protected void OnChange(PropertyChange ...
- 新兵易学,老兵易用----C++(C++11的学习整理---如何减少代码量,加强代码的可读性)
1.auto类型推导 auto推导最大的优势就是在拥有初始化表达式的复杂类型变量声明时简化代码. auto第二个优势就是免去了程序员在一些类型声明时的麻烦,或者避免一些在类型声明时的错误. auto第 ...
- Java 8 中的方法引用,轻松减少代码量,提升可读性!
1. 引言 Java8中最受广大开发中喜欢的变化之一是因为引入了 lambda 表达式,因为这些表达式允许我们放弃匿名类,从而大大减少了样板代码,并提高了可读性. 方法引用是lambda表达式的一种特 ...
- 一些减少代码量、提高开发效率的利器(Java)
Spring Boot mybatis-plus代码生成器和自带CRUD接口 lombok 库: Apache Commons & guava AOP Java8: stream & ...
- springboot 使用 @data 插件,减少代码量
一.idea 安装 lombok 插件 二.重启 idea 三.添加依赖 <dependency> <groupId>org.projectlombok</groupId ...
- 让你的代码量减少3倍!使用kotlin开发Android(一)
让你的代码量减少3倍!使用kotlin开发Android(一) 创建Kotlin工程 本文同步自博主的私人博客:wing的地方酒馆 写在前面 使用kotlin开发android已经两周多了.得到的好处 ...
- 让你的代码量减少3倍!使用kotlin开发Android(二) --秘笈!扩展函数
本文承接上一篇文章:让你的代码量减少3倍!使用kotlin开发Android(一) 创建Kotlin工程 本文同步自博主的私人博客wing的地方酒馆 上一节说到,kotlin可以省去getter,se ...
- 单位分配的IP地址和电脑主机绑定了,我想用设置一个无线路由器,让我的笔记本电脑和手机都能上网?
单位分配的IP地址和电脑主机绑定了,我想用设置一个无线路由器,让我的笔记本电脑和手机都能上网? 配一个无线路由器就可以实现,将电脑IP配置成自动获取,找条网线一头插路由LAN口(路由器上有标明 ...
随机推荐
- 最小生成树MST算法(Prim、Kruskal)
最小生成树MST(Minimum Spanning Tree) (1)概念 一个有 n 个结点的连通图的生成树是原图的极小连通子图,且包含原图中的所有 n 个结点,并且有保持图连通的最少的边,所谓一个 ...
- Python 远程开发环境部署与调试
一.下载相应开发工具 Pycharm :下载地址 二.部署开发机 一般在工作过程中,开发环境并不是本地环境,而是指在开发机:因为,有很多依赖本地部署非常麻烦,而开发机中则内置了很多相关的服务 三.代 ...
- hdu5197 DZY Loves Orzing(FFT+分治)
hdu5197 DZY Loves Orzing(FFT+分治) hdu 题目描述:一个n*n的矩阵里填入1~n^2的数,要求每一排从前往后能看到a[i]个数(类似于身高阻挡视线那种),求方案数. 思 ...
- Redis数据库的初步认识(二)-C/C++连接redis数据库
1用C语言连接数据库,首先要安装c语言的数据库 在目录/redis- 4.0.1/deps下面执行sudo make/make install命令 在执行完之后可能执行ldconfig命令来更新连接符 ...
- grep 命令?
强大的文本搜索命令,grep(Global Regular Expression Print) 全局正则表达式搜索.grep 的工作方式是这样的,它在一个或多个文件中搜索字符串模板.如果模板包括空格, ...
- maven常用命令含义
今天在开发过程中,对一个mapper.xml文件的sql进行了改动,重启tomcat后发现没有生效,首先考虑是不是远程服务开启着,导致代码没有走本地,确认远程服务是关闭的,的确是本地修改没有生效,于是 ...
- js的json序列化和反序列化
(1)序列化 即js中的Object转化为字符串 1.使用toJSONString var last=obj.toJSONString(); //将JSON对象转化为JSON字符 2.使用string ...
- JAVA DAEMON线程的理解
java线程分两种:用户线程和daemon线程.daemon线程或进程就是守护线程或者进程,但是java中所说的daemon线程和linux中的daemon是有一点区别的. linux中的daemon ...
- BUG战斗史 —— 日期格式与字符串之间的转换
说在前面 最近在公司实习,接触了一个中小型的后台管理系统,不得不说,项目的目录结构比我平时做的"课程设计"要来得复杂,于是我先去看了Github上一些后台管理系统的模板项目 在gu ...
- vim的vimrc配置
windows "# modified by Neoh set helplang=cn "使用中文帮助文档 set encoding=utf-8 "查看utf-8格式的帮 ...