parent
64772323fc
commit
ae03fdad47
@ -0,0 +1,57 @@
|
||||
// 声明类所在的包为 com.utils
|
||||
package com.utils;
|
||||
|
||||
// 导入 Spring 框架中处理 Bean 相关异常的类
|
||||
import org.springframework.beans.BeansException;
|
||||
// 导入 Spring 框架的应用上下文接口,代表 Spring 应用的上下文环境
|
||||
import org.springframework.context.ApplicationContext;
|
||||
// 导入 Spring 框架的应用上下文感知接口,实现该接口可获取应用上下文
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
// 导入 Spring 框架的组件注解,用于将类标记为 Spring 组件
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
// 使用 @Component 注解将该类标记为 Spring 组件,使其能被 Spring 自动扫描和管理
|
||||
@Component
|
||||
// 定义 SpringContextUtils 类,实现 ApplicationContextAware 接口以获取 Spring 应用上下文
|
||||
public class SpringContextUtils implements ApplicationContextAware {
|
||||
// 定义一个静态的 ApplicationContext 类型变量,用于存储 Spring 应用上下文
|
||||
public static ApplicationContext applicationContext;
|
||||
|
||||
// 重写 ApplicationContextAware 接口的方法,当 Spring 容器初始化时会调用此方法
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
// 将传入的应用上下文赋值给类的静态变量,方便后续静态方法使用
|
||||
SpringContextUtils.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
// 定义静态方法,根据 Bean 的名称从应用上下文中获取对应的 Bean 实例
|
||||
public static Object getBean(String name) {
|
||||
// 调用应用上下文的 getBean 方法,通过名称获取 Bean 实例
|
||||
return applicationContext.getBean(name);
|
||||
}
|
||||
|
||||
// 定义泛型静态方法,根据 Bean 的名称和所需类型从应用上下文中获取指定类型的 Bean 实例
|
||||
public static <T> T getBean(String name, Class<T> requiredType) {
|
||||
// 调用应用上下文的 getBean 方法,通过名称和类型获取 Bean 实例
|
||||
return applicationContext.getBean(name, requiredType);
|
||||
}
|
||||
|
||||
// 定义静态方法,用于判断应用上下文中是否包含指定名称的 Bean
|
||||
public static boolean containsBean(String name) {
|
||||
// 调用应用上下文的 containsBean 方法进行判断
|
||||
return applicationContext.containsBean(name);
|
||||
}
|
||||
|
||||
// 定义静态方法,用于判断指定名称的 Bean 是否为单例模式
|
||||
public static boolean isSingleton(String name) {
|
||||
// 调用应用上下文的 isSingleton 方法进行判断
|
||||
return applicationContext.isSingleton(name);
|
||||
}
|
||||
|
||||
// 定义静态方法,用于获取指定名称的 Bean 的类型
|
||||
public static Class<? extends Object> getType(String name) {
|
||||
// 调用应用上下文的 getType 方法获取 Bean 的类型
|
||||
return applicationContext.getType(name);
|
||||
}
|
||||
}
|
Loading…
Reference in new issue