静态类获取bean

在开发中经常遇到spring无法将bean注入到静态类或new Object()中,所以查找资料后发现可以在ApplicationContext(上下文)中获取;

工具类

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

@Component
public class SpringBeanUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

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

    public static <T> T getObject(Class<T> tClass) {
        return applicationContext.getBean(tClass);
    }

    public static Object getBean(String tClass) {
        return applicationContext.getBean(tClass);
    }

    public <T> T getBean(Class<T> tClass) {
        return applicationContext.getBean(tClass);
    }

}
发布了2 篇原创文章 · 获赞 0 · 访问量 27

猜你喜欢

转载自blog.csdn.net/qq_32517803/article/details/103984968