Spring获取Bean的几种方式

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

方法一在初始化时保存ApplicationContext对象

ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml"); 
ac.getBean("userService");
 
//比如在application.xml中配置
<bean id="userService" class="com.cloud.service.impl.UserServiceImpl"></bean>

说明这样的方式适用于Spring框架的独立应用程序需要程序通过配置文件初始化Spring。

方法二通过Spring提供的工具类获取ApplicationContext对象

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc); 
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc); 
ac1.getBean("beanId"); 
ac2.getBean("beanId");  

说明这样的方式适合于采用Spring框架的B/S系统通过ServletContext对象获取ApplicationContext对象。然后在通过它获取须要的类实例。上面两个工具方式的差别是前者在获取失败时抛出异常。后者返回null。

方法三实现接口ApplicationContextAware推荐

/**
 * Spring ApplicationContext 工具类
*/
@SuppressWarnings("unchecked")
@Component
public class SpringUtils implements ApplicationContextAware {
 
    private static ApplicationContext applicationContext;
 
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }
 
    public static <T> T getBean(String beanName) {
        if(applicationContext.containsBean(beanName)){
            return (T) applicationContext.getBean(beanName);
        }else{
            return null;
        }
    }
 
    public static <T> Map<String, T> getBeansOfType(Class<T> baseType){
        return applicationContext.getBeansOfType(baseType);
    }
}

说明实现该接口的setApplicationContext(ApplicationContext context)方法并保存ApplicationContext 对象。Spring初始化时扫描到该类就会通过该方法将ApplicationContext对象注入。然后在代码中就可以获取spring容器bean了。例如

LoadExploreTree bean = SpringUtils.getBean(“loadExploreTree”);

方法四继承自抽象类ApplicationObjectSupport

@Service
public class SpringContextHelper2 extends ApplicationObjectSupport {
    
    
    //提供一个接口获取容器中的Bean实例根据名称获取
    public Object getBean(String beanName)
    {
        return getApplicationContext().getBean(beanName);
    }
    
}

继承类的方式是调用父类的getApplicationContext()方法获取Spring容器对象。

方法五继承自抽象类WebApplicationObjectSupport

说明类似上面方法。调用getWebApplicationContext()获取WebApplicationContext

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring