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

spring boot 获取ApplicationContext

程序员文章站 2022-05-25 10:57:28
...

https://www.jianshu.com/p/fa5db63a12e5

@Component
@Lazy(false)
public class SpringContext implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}
  1. 使用:
//通过class获得bean
UserService userService= SpringContext.getBean(UserService.class);
//通过name获得bean
UserService userService= SpringContext.getBean("userService");
//通过name,以及Clazz返回指定的Bean
UserService userService= SpringContext.getBean("userService",UserService.class);