在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);
    }
}
相关文章
相关标签/搜索