|
|
|
@ -1,4 +1,3 @@
|
|
|
|
|
|
|
|
|
|
package com.utils;
|
|
|
|
|
|
|
|
|
|
import org.springframework.beans.BeansException;
|
|
|
|
@ -6,38 +5,78 @@ import org.springframework.context.ApplicationContext;
|
|
|
|
|
import org.springframework.context.ApplicationContextAware;
|
|
|
|
|
import org.springframework.stereotype.Component;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Spring Context 工具类
|
|
|
|
|
* 该类实现了 ApplicationContextAware 接口,用于在 Spring 应用中获取 ApplicationContext 实例,
|
|
|
|
|
* 从而可以在非 Spring 管理的类中方便地获取 Spring 容器中的 Bean。
|
|
|
|
|
*/
|
|
|
|
|
@Component
|
|
|
|
|
public class SpringContextUtils implements ApplicationContextAware {
|
|
|
|
|
public static ApplicationContext applicationContext;
|
|
|
|
|
|
|
|
|
|
// 静态的 ApplicationContext 实例,用于存储 Spring 应用上下文
|
|
|
|
|
public static ApplicationContext applicationContext;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 实现 ApplicationContextAware 接口的方法,Spring 容器会在启动时自动调用该方法,
|
|
|
|
|
* 将 ApplicationContext 实例注入到本类中。
|
|
|
|
|
*
|
|
|
|
|
* @param applicationContext Spring 应用上下文实例
|
|
|
|
|
* @throws BeansException 如果在设置 ApplicationContext 时发生错误
|
|
|
|
|
*/
|
|
|
|
|
@Override
|
|
|
|
|
public void setApplicationContext(ApplicationContext applicationContext)
|
|
|
|
|
throws BeansException {
|
|
|
|
|
SpringContextUtils.applicationContext = applicationContext;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 根据 Bean 的名称从 Spring 容器中获取 Bean 实例。
|
|
|
|
|
*
|
|
|
|
|
* @param name Bean 的名称
|
|
|
|
|
* @return 对应的 Bean 实例
|
|
|
|
|
*/
|
|
|
|
|
public static Object getBean(String name) {
|
|
|
|
|
return applicationContext.getBean(name);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 根据 Bean 的名称和类型从 Spring 容器中获取指定类型的 Bean 实例。
|
|
|
|
|
*
|
|
|
|
|
* @param name Bean 的名称
|
|
|
|
|
* @param requiredType Bean 的类型
|
|
|
|
|
* @param <T> Bean 的泛型类型
|
|
|
|
|
* @return 对应的 Bean 实例
|
|
|
|
|
*/
|
|
|
|
|
public static <T> T getBean(String name, Class<T> requiredType) {
|
|
|
|
|
return applicationContext.getBean(name, requiredType);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 检查 Spring 容器中是否包含指定名称的 Bean。
|
|
|
|
|
*
|
|
|
|
|
* @param name Bean 的名称
|
|
|
|
|
* @return 如果包含返回 true,否则返回 false
|
|
|
|
|
*/
|
|
|
|
|
public static boolean containsBean(String name) {
|
|
|
|
|
return applicationContext.containsBean(name);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 检查指定名称的 Bean 是否为单例模式。
|
|
|
|
|
*
|
|
|
|
|
* @param name Bean 的名称
|
|
|
|
|
* @return 如果是单例返回 true,否则返回 false
|
|
|
|
|
*/
|
|
|
|
|
public static boolean isSingleton(String name) {
|
|
|
|
|
return applicationContext.isSingleton(name);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 获取指定名称的 Bean 的类型。
|
|
|
|
|
*
|
|
|
|
|
* @param name Bean 的名称
|
|
|
|
|
* @return Bean 的类型
|
|
|
|
|
*/
|
|
|
|
|
public static Class<? extends Object> getType(String name) {
|
|
|
|
|
return applicationContext.getType(name);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|