在Bean中获取spring 容器 并通过容器获取容器中其他bean

spring 提供了Awear 接口去 让bean 能感受到外界的环境。Awear 接口有很多实现,常用的有

ApplicationContextAware (可以通过实现这个接口去获取ApplicationContext),
BeanNameAware(可以获取Bean自身的一些属性),
BeanFactoryAware(可以获取BeanFactory)
@Component
public class ApplicationContextManager implements ApplicationContextAware{

    private   static  ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("---------------------添加Application--------------------------");
         if(ApplicationContextManager.applicationContext == null){
             ApplicationContextManager.applicationContext = applicationContext;
         }
    }

    public static   ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    /**
     * 通过name 获取Bean
     */
    public static Object getBean(String beanName){
      return   applicationContext.getBean(beanName);
    }

    public static <T> T getBean(String beanName,Class<T> clazz){
        return  applicationContext.getBean(beanName,clazz);
    }

    public static <T> T getBean(Class<T> clazz){
        return  applicationContext.getBean(clazz);
    }
}
原文地址:https://www.cnblogs.com/li-zhi-long/p/10956254.html