在Bean中獲取spring 容器 並經過容器獲取容器中其餘bean

spring 提供了Awear 接口去 讓bean 能感覺到外界的環境。Awear 接口有不少實現,經常使用的有spring

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);
    }
}
相關文章
相關標籤/搜索