Springcloud学习笔记52--通过ApplicationContextAware接口从spring上下文中获取到需要的bean(获取spring托管的Bean)

1.背景

在spring项目中,bean之间的依赖关系是 spring容器自动管理的,但是一个项目中有些类不在spring容器中却需要使用spring管理的bean,这时候不能通过正常的方式(注解等方式)注入bean,在spring中提供了ApplicationContextAware接口,通过ApplicationContextAware接口可以获取到spring上下文,从而从spring上下文中获取到需要的bean。

2 ApplicationContext 通过 getBean方法

详细介绍Spring容器 ApplicationContext 通过 getBean方法 获取实例的几种方式;

3.SpringUtils.java

我们可以编写一个工具类来实现ApplicationContextAware,通过工具类来获取我们需要的bean在spring容器外的类调用bean的方法,具体代码如下:

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

//此处使用注解的方式把工具类加入到容器中,可以使用xml,配置类等方式,必须要加入到容器中
@Component
public class SpringUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;  
  //此方法是父类ApplicationContextAware 中的方法 重写
    @Override  
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
        if(SpringUtils.applicationContext == null){  
            SpringUtils.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);  
    }
}

容器外类 TestAppContext.java

public class TestAppContext{
    //因为Person是容器中的bean TestAppContext不受spring容器管理 所以
    //这里不能通过正常的方式注入
    private Person person;
    public String getPersonName(){
        //通过bean的名称来获取bean
        person = (Person)SpringUtils.getBean("person");
        person2 = (Person)SpringUtils.getBean(Person.class);
        return person.getName(); } 
}

参考文献:https://blog.csdn.net/qq_28070019/article/details/83624380

posted @ 2022-11-22 10:51  雨后观山色  阅读(527)  评论(0)    收藏  举报