SpringBoot中如何获取容器中配置的bean对象?

码云
2020-11-26 11:08

springboot动态获取容器中配置的bean可以参考下面的代码:

package com.findsrc.common.util;

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

@Service
public class ContextUtil implements ApplicationContextAware {

	private ApplicationContext context;

	private static ContextUtil instance;

	public ContextUtil() {
		instance = this; //赋值给静态对象
	}

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

    //提供静态访问
	public static <T> T getBean(Class<T> cls) {
		return instance.context.getBean(cls);
	}

    //提供静态访问
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		return (T) instance.context.getBean(name);
	}
}

 

使用方式如下:

ContextUtil.getBean("beanName");
//这个方法有缺点,就是最好不要在应用启动的时候使用,因为有可能ApplicationContext尚未注入。

 

全部评论