欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring环境下非注入类获取注入类的对象

程序员文章站 2022-05-25 22:56:35
...

继承ApplicationContextAware实现工具类:

@Component
public class SpringContextUtil implements ApplicationContextAware
{
    private static ApplicationContext applicationContext = null;
    
    @Override
    public void setApplicationContext(ApplicationContext context)
        throws BeansException
    {
        if (applicationContext == null)
        {
            applicationContext = context;
        }
    }
    
    public static ApplicationContext getApplicationContext()
    {
        return applicationContext;
    }
    
    public static <T> T getBean(Class<T> clazz)
    {
        return getApplicationContext().getBean(clazz);
    }
    
    public static final Object getBean(String beanName)
    {
        return getApplicationContext().getBean(beanName);
    }
}

在非Spring托管的类中获取Spring容器中托管的对象