Aware接口作用

news2024/10/7 8:27:17

介绍

Aware(感知)接口是一个标记,里面没有任何方法,实际方法定义都是子接口确定(相当于定义了一套规则,并建议子接口中应该只有一个无返回值的方法)。

我们知道spring已经定义好了很多对象,如ApplicationContext、BeanFactory、Environment等,但是这些对象是spring框架自身的,我们去获取这些是及其困难的,所以spring定义了一套规则能让我们很容易得获取框架中的对象,这就是Aware的意义,现在对Aware有一定了解了吧,Aware是感知spring容器中的对象。

spring定义了很多子接口并已实现可直接可用,下图均为spring中的子接口。
在这里插入图片描述
如图第一个ApplicationContextAware,类名很清晰的告诉我们是感知ApplicationContext,ApplicationContext都知道是spring容器,所以这里表示感知容器,就是我们想获取ApplicationContext只需要实现这个接口就行。

注意
这里的接口名都是有规则的,如ApplicationContextAware就是获取ApplicationContext的,BeanFactoryAware就是获取BeanFactory的,见名知意。

源码

public interface ApplicationContextAware extends Aware {

	/**
	 * 只有一个方法,实现这方法spring在启动过程中会默认将
	 * 调用此方法并将ApplicationContext参数传递过来,这样
	 * 我们就能很容易的获取到ApplicationContext了
	 */
	void setApplicationContext(ApplicationContext applicationContext) throws BeansException;

}

例子

Teacher类并实现ApplicationContextAware 接口

package com.lp.entity;


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class Teacher implements ApplicationContextAware {
	private String name;

	private ApplicationContext applicationContext;

	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Teacher{" +
				"name='" + name + '\'' +
				'}';
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext =applicationContext;
	}
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
	<context:component-scan base-package="com.lp"/>

	<bean id="teacher" class="com.lp.entity.Teacher">
		<property name="name" value="zhangsan"/>
	</bean>
</beans>

测试,看一看Teacher类中能不能获取到ApplicationContext对象

package example.lp;

import com.lp.entity.Teacher;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class test {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
		Teacher teacher = (Teacher)context.getBean("teacher");
		System.out.println("------------ApplicationContext="+teacher.getApplicationContext());
	}
}

在这里插入图片描述
从结果中可以清晰的看到已经获取到了ApplicationContext对象,当我们需要其他对象也可以看看其他Aware子接口,直接实现即可。

自定义Aware接口(简单看一下)

spring中有一个ApplicationContextAwareProcessor类,里面就是实现这些子接口功能的,invokeAwareInterfaces方法就是具体逻辑。

class ApplicationContextAwareProcessor implements BeanPostProcessor {

	private final ConfigurableApplicationContext applicationContext;

	private final StringValueResolver embeddedValueResolver;


	/**
	 * Create a new ApplicationContextAwareProcessor for the given context.
	 */
	public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
		this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
	}


	@Override
	@Nullable
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if (bean instanceof Aware) {
			invokeAwareInterfaces(bean);
		}
		return bean;
	}

	private void invokeAwareInterfaces(Object bean) {
		if (bean instanceof EnvironmentAware environmentAware) {
			environmentAware.setEnvironment(this.applicationContext.getEnvironment());
		}
		if (bean instanceof EmbeddedValueResolverAware embeddedValueResolverAware) {
			embeddedValueResolverAware.setEmbeddedValueResolver(this.embeddedValueResolver);
		}
		if (bean instanceof ResourceLoaderAware resourceLoaderAware) {
			resourceLoaderAware.setResourceLoader(this.applicationContext);
		}
		if (bean instanceof ApplicationEventPublisherAware applicationEventPublisherAware) {
			applicationEventPublisherAware.setApplicationEventPublisher(this.applicationContext);
		}
		if (bean instanceof MessageSourceAware messageSourceAware) {
			messageSourceAware.setMessageSource(this.applicationContext);
		}
		if (bean instanceof ApplicationStartupAware applicationStartupAware) {
			applicationStartupAware.setApplicationStartup(this.applicationContext.getApplicationStartup());
		}
		if (bean instanceof ApplicationContextAware applicationContextAware) {
			applicationContextAware.setApplicationContext(this.applicationContext);
		}
	}

}

自己实现Aware接口

这个需要了解一下spring启动过程,跟BeanPostProcessor这个接口有关,也需要了解BeanPostProcessor的执行时机,这里我就不介绍了,我自己写了一个示例,这里只是展示怎么实现Aware的。

package com.lp.entity;


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class Teacher implements ApplicationContextAware {
	private String name;

	private ApplicationContext applicationContext;

	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Teacher{" +
				"name='" + name + '\'' +
				'}';
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext =applicationContext;
	}
}
package com.lp.entity;

import com.lp.TeacherAware;

public class Student implements TeacherAware {
	private String name;

	private Teacher teacher;

	public Teacher getTeacher() {
		return teacher;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public void setTeacher(Teacher teacher) {
		this.teacher =teacher;
	}
}

package com.lp;

import com.lp.entity.Teacher;
import org.springframework.beans.factory.Aware;

public interface TeacherAware extends Aware {
	void setTeacher(Teacher teacher);
}

package com.lp;

import com.lp.entity.Teacher;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class TeacherAwareBeanPostProcessor implements BeanPostProcessor {
	private final ConfigurableApplicationContext applicationContext;

	@Autowired
	public TeacherAwareBeanPostProcessor(ConfigurableApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if (bean instanceof TeacherAware teacherAware){
			teacherAware.setTeacher(applicationContext.getBean(Teacher.class));
		}
		return bean;
	}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
	<context:component-scan base-package="com.lp"/>

	<bean id="teacher" class="com.lp.entity.Teacher">
		<property name="name" value="zhangsan"/>
	</bean>
	<bean id="student" class="com.lp.entity.Student">
		<property name="name" value="lisi"/>
	</bean>

</beans>
package example.lp;

import com.lp.entity.Student;
import com.lp.entity.Teacher;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class test {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
		//Teacher teacher = (Teacher)context.getBean("teacher");
		//System.out.println("------------ApplicationContext="+teacher.getApplicationContext());

		Student student = (Student)context.getBean("student");
		System.out.println("------------Teacher="+student.getTeacher());
	}
}

从上述代码和结果中可以看到,我创建了两个bean,一个Student和一个Teacher,我用Aware方式实现了将Student中的Teacher属性注入,当然这个场景可能不是很合适,但这里主要是演示怎么自己实现Aware接口,需要自己写一个接口实现Aware接口并之定义一个方法(接口名最好是遵循spring规则,且只有一个void方法),创建一个实现BeanPostProcessor的对象并写出具体实现逻辑,这儿需要你了解spring启动流程并且知道BeanPostProcessor接口的作用。

希望对你有帮助,别忘了点赞!!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1686860.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

深入解析R语言的贝叶斯网络模型:构建、优化与预测;INLA下的贝叶斯回归;现代贝叶斯统计学方法;R语言混合效应(多水平/层次/嵌套)

目录 ①基于R语言的贝叶斯网络模型的实践应用 ②R语言贝叶斯方法在生态环境领域中的应用 ③基于R语言贝叶斯进阶:INLA下的贝叶斯回归、生存分析、随机游走、广义可加模型、极端数据的贝叶斯分析 ④基于R语言的现代贝叶斯统计学方法&#xff08;贝叶斯参数估计、贝叶斯回归、…

Python 实现批量文件重命名工具

在现代软件开发中&#xff0c;图形用户界面 (GUI) 工具的创建是一个常见需求。对于那些需要频繁处理文件的任务&#xff0c;拥有一个简便的 GUI 工具尤为重要。在这篇博客中&#xff0c;我们将介绍如何使用 wxPython 创建一个简单的批量文件重命名工具。该工具可以选择一个文件…

AWS EC2 连接 AWS RDS(Mysql)

1 创建RDS数据库 点击创建数据库 引擎选项 模板 设置 连接 2 EC2连接Mysql $ sudo yum list mariadb* Installed Packages mariadb-connector-c.x86_64 3.1.13-1.amzn2023.0.3 amazonl…

Flutter笔记:Widgets Easier组件库-使用隐私守卫

Flutter笔记 Widgets Easier组件库&#xff1a;使用隐私守卫 - 文章信息 - Author: 李俊才 (jcLee95) Visit me at CSDN: https://jclee95.blog.csdn.netMy WebSite&#xff1a;http://thispage.tech/Email: 291148484163.com. Shenzhen ChinaAddress of this article:https:…

签发免费https证书的方式

目录 http访问和https访问的区别 实现https后有哪些好处&#xff1a; 如何申请、安装部署免费https证书&#xff1a; 在浏览网页时&#xff0c;最常见的是http访问&#xff0c;但是也有一部分网站前缀是https&#xff0c;且浏览器网址栏会出现“安全”字样&#xff0c;或是绿…

【C++】<图形库> EasyX基础使用

文章目录 一、安装EasyX库 二、图形窗口显示 三、基本绘图函数 四、图片显示 五、键盘交互 六、鼠标交互 七、双缓冲区解决闪屏 一、安装EasyX库 已经有兄弟写得很清楚了&#xff0c;见EasyX | 安装教程&#xff08;详细图文&#xff09;。 二、图形窗口显示 1. 包含的…

深度学习之基于Tensorflow+Flask框架Web手写数字识别

欢迎大家点赞、收藏、关注、评论啦 &#xff0c;由于篇幅有限&#xff0c;只展示了部分核心代码。 文章目录 一项目简介 二、功能三、系统四. 总结 一项目简介 一、项目背景与意义 手写数字识别是深度学习领域中的一个经典问题&#xff0c;也是计算机视觉领域的重要应用之一。…

【加密与解密(第四版)】第二十一章笔记

第二十一章 VMProtect逆向和还原浅析 21.1 VMProtect逆向分析 21.2 VMProtect的还原 不行了&#xff0c;一点都看不懂

centos7和centos8安装mysql5.6 5.7 8.0

https://dev.mysql.com/downloads/repo/yum/ 注意构造下http://repo.mysql.com/mysql-community-release-el*-*.noarch.rpm 【以centos7为例】 安装mysql5.6 wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm rpm -ivh mysql-community-release-el7-5…

推荐网站(17)audiohub免费音乐平台

今天&#xff0c;我要向您推荐一个非常实用的网站——AudioHub。这是一个提供免费音乐的平台&#xff0c;特别适合需要无版权音乐资源的创作者、视频制作人、播客主持人以及任何需要背景音乐的项目。里面的音乐无版权&#xff0c;可商用。 链接直达&#xff1a;https://audiohu…

移动硬盘不显示容量与无法访问问题的解决方案及预防措施

在日常生活和工作中&#xff0c;移动硬盘已成为我们存储数据的重要工具。然而&#xff0c;当遇到移动硬盘不显示容量或无法访问的情况时&#xff0c;我们该如何应对&#xff1f;本文将详细介绍这一问题的现象、原因&#xff0c;并提供两种有效的数据恢复方案&#xff0c;同时还…

深度学习之基于Pytorch框架多人多摄像头摔倒跌倒坠落检测

欢迎大家点赞、收藏、关注、评论啦 &#xff0c;由于篇幅有限&#xff0c;只展示了部分核心代码。 文章目录 一项目简介 二、功能三、系统四. 总结 一项目简介 一、项目背景 随着智能监控技术的广泛应用&#xff0c;对于公共场合的安全监控需求日益增加。摔倒跌倒坠落是常见的…

申请公众号数量达标

一般可以申请多少个公众号&#xff1f;目前企业主体只能申请2个公众号&#xff0c;这也意味着想做矩阵公众号的难度提升了。有些公司靠着诸多不同分工的公众号形成一个个矩阵&#xff0c;获取不同领域的粉丝。比如&#xff0c;目前主体为xx旗下公众号&#xff0c;共有30个&…

太阳诱电:顺应时代需求的新型电容器为何能在全球得到广泛应用(下)

随着汽车电动化和电子控制化的进展&#xff0c;车载计算机和电气部件也在逐渐向大功率化的方向发展。而构成这些车载设备电源电路的电子元器件也必须随之进行技术革新。太阳诱电集团携手全资子公司ELNA&#xff0c;开发并供应新型电容器“导电性高分子混合铝电解电容器”&#…

Vue前端项目打包,并部署Vue项目到Linux云服务器上

一. vue前端项目打包 1.使用vscode开发项目 2.在config目录下的prod.env.js文件当中配置我们后端服务器的IP地址和端口号&#xff0c;因为这是在实际的部署当中所以必须要在生成环境下进行项目的部署。 如图所示&#xff1a; 3.在config目录下的index.js文件当中要改assetsPu…

chrome125.0.6422.60驱动包下载

百度网盘地址:https://pan.baidu.com/s/1DAr_O58GQ6m4sk_QePZscA?pwd=5t0j 提取码:5t0j Chrome驱动包(ChromeDriver)是一个用于支持自动化测试的工具,它提供了对Google Chrome浏览器的控制,使您可以编写和运行自动化脚本来测试网站。这个驱动程序是由Selenium项目开…

今日arXiv最热大模型论文:LoRA又有新用途,学得少忘得也少,成持续学习关键!

自大模型&#xff08;LLM&#xff09;诞生以来&#xff0c;苦于其高成本高消耗的训练模式&#xff0c;学界和业界也在努力探索更为高效的参数微调方法。其中Low-Rank Adaptation&#xff08;LoRA&#xff09;自其诞生以来&#xff0c;就因其较低的资源消耗而受到广泛关注和使用…

Qt输入输出类使用总结

Qt输入输出类简介 QTextStream 类(文本流)和 QDataStream 类(数据流)Qt 输入输出的两个核心类,其作用分别如下: QTextStream 类:用于对数据进行文本格式的读/写操作,可在 QString、QIODevice或 QByteArray 上运行,比如把数据输出到 QString、QIODevice 或 QByteArray 对象…

Mysql命令行客户端常用命令

Mysql命令行客户端常用命令 注意点 下面展示的 database_name、table_name、column1、column2、value1、value2 和 datatype在自己用的时候需要替换为实际的值 在敲命令的时候要注意&#xff0c;一定要在末尾加上分号 操作 安装好Mysql之后&#xff0c;搜索找到以下应用 打…

QQ沐个人引导页html源码

好看的QQ沐个人引导页html源码&#xff0c;鼠标移动滑出美丽的线条收缩特效&#xff0c;界面美观大气&#xff0c;源码由HTMLCSSJS组成&#xff0c;记事本打开源码文件可以进行内容文字之类的修改&#xff0c;双击html文件可以本地运行效果&#xff0c;也可以上传到服务器里面 …