获取Spring上下文已实例化的bean
程序员文章站
2022-05-23 10:19:46
...
package com.example.demo;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* 获取Spring上下文已实例化的bean
*
* @author lzk
* @version 1.0
* @date 2020/12/8 14:15
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext context = null;
private SpringContextUtil() {
super();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
/**
* 根据名称获取bean
* @param beanName
* @return
*/
public static Object getBean(String beanName) {
return context.getBean(beanName);
}
/**
* 根据bean名称获取指定类型bean
* @param beanName bean名称
* @param clazz 返回的bean类型,若类型不匹配,将抛出异常
*/
public static <T> T getBean(String beanName, Class<T> clazz) {
return context.getBean(beanName, clazz);
}
/**
* 根据类型获取bean
* @param clazz
* @return
*/
public static <T> T getBean(Class<T> clazz) {
T t = null;
Map<String, T> map = context.getBeansOfType(clazz);
for (Map.Entry<String, T> entry : map.entrySet()) {
t = entry.getValue();
}
return t;
}
/**
* 是否包含bean
* @param beanName
* @return
*/
public static boolean containsBean(String beanName) {
return context.containsBean(beanName);
}
/**
* 是否是单例
* @param beanName
* @return
*/
public static boolean isSingleton(String beanName) {
return context.isSingleton(beanName);
}
/**
* bean的类型
* @param beanName
* @return
*/
public static Class getType(String beanName) {
return context.getType(beanName);
}
}
推荐阅读
-
Spring启动后获取所有拥有特定注解的Bean实例代码
-
02Spring基于xml的IOC配置--实例化Bean的三种方式
-
Spring Bean的实例化之属性注入源码剖析过程
-
Spring实例化Bean的五种方式
-
聊聊spring之bean对象的实例化过程
-
spring配置文件(spring的开发步骤;bean中的scope,init-method,destroy-method;bean的工厂静态方法实例化;工厂动态方法实例化)
-
Spring之bean的实例化和依赖注入
-
Spring | IOC之Bean的三种实例化
-
Spring Bean的获取与实例化
-
Spring --- Bean的获取、实例化与作用域