一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Spring获取管理对象常用方法代码详解

时间:2020-10-21 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Spring获取管理对象常用方法代码详解,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

第一种:

直接初始化Spring容器,获得对象

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

applicationContext.getBean("beanId");

关于配置文件的读取也有好多种,我用到的是配置文件在SRC下面。

这样会初始化Spring容器,然后再得到配置的对象。

第二种:

通过环境来获得

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());

ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());

ac1.getBean("beanId");

ac2.getBean("beanId");

区别是前者会抛异常,而后者没有时返回NULL

第三种:

实现ApplicationContextAware接口

下面给出实现类,这也是我用的方法

import org.springframework.beans.BeansException; 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.ApplicationContextAware; 
/** 
 * @说明 获得Spring配置中的某个对象 
 * @author 崔素强 
 * @see 
 */ 
public class SpringFactory implements ApplicationContextAware { 
  private static ApplicationContext context; 
  @SuppressWarnings("static-access") 
  @Override 
  public void setApplicationContext(ApplicationContext applicationContext) 
      throws BeansException { 
    this.context = applicationContext; 
  } 
  public static Object getObject(String id) { 
    Object object = null; 
    object = context.getBean(id); 
    return object; 
  } 
} 

热门栏目