在new对象中,使用spring bean对象2021-10-23

一、背景

https://www.jianshu.com/p/4c0723615a52

创建ApplicationContextUtil,是为了能在java new的对象中,使用getBean方法,方便获取bean对象。

二、用法

/**
@Lazy(value=true)
使用该对象的时候再加载ApplicationContextUtil
会减少springIoc启动时候消耗的时间
**/
@Component
@Lazy(value=true)
public class ApplicationContextUtil implements ApplicationContextAware {
    private Map<String,ApplicationContext> contexts = new ConcurrentHashMap<>(16);	
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    /**
    要想使用这个对象,那么就需要先创建这个对象
	**/
        synchronized (contexts) {
     contexts.put(applicationContext.getId(), applicationContext);
        }
    }
 
    public <T> T  getBean(String id, String name) {
    // 先判断是否包含该id
    if (!contexts.containsKey(id)) {
    	return null;
	}
        //name表示其他要注入的注解name名
        return (T) contexts.get(id).getBean(name);
    }
 
    public <T> T getBean(String id, Class<T> classType) {
    	if (!contexts.containsKey(id)) {
    	return null;
	}
        return contexts.get(id).getBean(classType);
    }
	
	/**
	获取对应name,对应class的bean对象
**/
	public <T> T getBean(String name, Class<T> classType) {
		
		if (Objects.isNull(name) || Objects.isNull(classType)) {
	return null;
	}

        for (ApplicationContext item : contexts.values()) {
            if (item.containsBean(name)) {
                return (T) item.getBean(name, classType);
            }
        }
    }
applicationContext怎么获取这个对象呢?
ApplicationContextUtil.setApplicationContext()ApplicationContextAwareProcessorinvokeAwareInterfaces(Object bean) 方法,对实现了Aware接口的bean进行注入相对应的实例。 
参考:
[链接](https://blog.csdn.net/canyanruxue/article/details/81181562)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值