`

Spring在应用中获得Bean的方法

阅读更多

一.使用ApplicationContext获得Bean

        首先新建一个类,该类必须实现ApplicationContextAware接口,改接口有一个方法,public void setApplicationContext(ApplicationContext applicationContext)throws BeansException,也就是说框架会自动调用这个方法返回一个ApplicationContext对象。具体类如下:

package com.bijian.study.test;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextUtils implements ApplicationContextAware {// Spring的工具类,用来获得配置文件中的bean

	private static ApplicationContext applicationContext = null;

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		SpringContextUtils.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public static Object getBean(String name) throws BeansException {
		return applicationContext.getBean(name);
	}

	public static Object getBean(String name, Class requiredType)
			throws BeansException {
		return applicationContext.getBean(name, requiredType);
	}

	public static boolean containsBean(String name) {
		return applicationContext.containsBean(name);
	}

	public static boolean isSingleton(String name)
			throws NoSuchBeanDefinitionException {
		return applicationContext.isSingleton(name);
	}

	public static Class getType(String name)
			throws NoSuchBeanDefinitionException {
		return applicationContext.getType(name);
	}

	public static String[] getAliases(String name)
			throws NoSuchBeanDefinitionException {
		return applicationContext.getAliases(name);
	}
}

        该类中有一个getBean(String name)方法,该方法用applicationContext去获得Bean实例,而applicationContext是由系统启动时自动设置的。

        注意,需要把该类在applicationContext.xml配置文件中进行注册。<bean id="springUtil" class="com.bijian.study.test.SpringContextUtils "/>

 

二.通过BeanFactory接口获得Bean

        也是新建一个类,不过该类需要实现BeanFactoryAware接口,该接口有一个方法public void setBeanFactory(BeanFactory beanFactory) throws BeansException;该方法是为了设置BeanFactory对象,系统会在启动的时候自动设置BeanFactory。具体代码如下:

package com.bijian.study.test;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

public class SpringBeanFactoryUtils implements BeanFactoryAware {

	private static BeanFactory beanFactory = null;
	private static SpringBeanFactoryUtils factoryUtils = null;

	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		SpringBeanFactoryUtils.beanFactory = beanFactory;
	}

	public static BeanFactory getBeanFactory() {
		return beanFactory;
	}

	public static SpringBeanFactoryUtils getInstance() {
		if (factoryUtils == null) {
			// factoryUtils =
			// (SpringBeanFactoryUtils)beanFactory.getBean("springBeanFactoryUtils");
			factoryUtils = new SpringBeanFactoryUtils();
		}
		return factoryUtils;
	}

	public static Object getBean(String name) {
		return beanFactory.getBean(name);
	}
}

        不过应该注意的是,改类中有一个getInstance方法,由于该代码是网上摘抄的,他提供了这么一个方法,目的是利用单例模式获得该类的一个实例,但由于getBean(String name)方法是静态的,所以用不用单例都无关紧要,经过测试,两种方法都行的通。

        另外一点就是必须把该类添加到applicationContext.xml的配置文件中<bean id="springBeanFactoryUtils" class="com.bijian.study.test.SpringBeanFactoryUtils"/>

 

三.在servlet中可以用WebApplicationContext类去获取Bean,具体做法是:

ServletContext context = request.getServletContext();
//ServletContext context = request.getSession().getServletContext();
WebApplicationContext webcontext = (WebApplicationContext)context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
helloService =  (HelloService) webcontext.getBean("helloService");
logger.info(helloService.processService("WebApplicationContext test"));

        其中context是servlet的上下文,在servlet中可以通过this.getServletContext()或者request.getSession().getServletContext();获得servletContext。但是一点,spring的配置文件必须在WEB-INF下。WebApplicationContext 有一个方法getBean(String name);其实WebApplicationContext 就是ApplicationContext的另一种形式而已。

        另外,在普通的java类中,即不是在servlet中可以用ContextLoader获得。ContextLoader是org.springframework.web.context包当中的一个类。

WebApplicationContext webApplication = ContextLoader.getCurrentWebApplicationContext(); 
helloService = (HelloService) webApplication.getBean("helloService");
logger.info(helloService.processService("ContextLoader.getCurrentWebApplicationContext() test"));

        用这种方法就能获取一个WebApplicationContext 的对象。

        最后经过测试,在重复100000次的基础上,第一二中方法只用了16毫秒,而第三种方法消耗了62毫秒,所以推荐使用第一二种方法。

 

四.非WEB项目

        即在java main函数中执行spring的代码,如下有四种方式。

package com.bijian.study.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

import com.bijian.study.service.HelloService;
  
public class Main {  
  
    public static void main(String[] args) throws Exception {
    	
    	String[] path1 = {"WebContent/WEB-INF/springMVC-servlet.xml"};  
        ApplicationContext context1 = new FileSystemXmlApplicationContext(path1);  
        HelloService helloService1 = context1.getBean(HelloService.class);  
        System.out.println(helloService1.processService("bijian"));  
          
        String path2="WebContent/WEB-INF/springMVC-servlet.xml";  
        ApplicationContext context2 = new FileSystemXmlApplicationContext(path2);  
        HelloService helloService2 = context2.getBean(HelloService.class);  
        System.out.println(helloService2.processService("bijian"));  
          
        ApplicationContext context = new FileSystemXmlApplicationContext("/WebContent/WEB-INF/springMVC-servlet.xml");  
        //HelloService helloService = context.getBean(HelloService.class);  
        HelloService helloService = (HelloService) context.getBean("helloService");  
        System.out.println(helloService.processService("bijian"));  
        
        GenericXmlApplicationContext context4 = new GenericXmlApplicationContext();  
        context4.setValidating(false);  
        context4.load("classpath:springMVC-servlet.xml");  
        context4.refresh();  
        HelloService helloService4 = context4.getBean(HelloService.class);
        System.out.println(helloService4.processService("bijian"));
    }  
}

        特别说明:context4.load("classpath:springMVC-servlet.xml");方式,需将springMVC-servlet.xml拷贝一份到src目录下,否则执行会报“class path resource [springMVC-servlet.xml] cannot be opened because it does not exist”,如下所示。


 

附:Web工程中验证的代码

@RequestMapping("/greeting")
public ModelAndView greeting(@RequestParam(value = "name", defaultValue = "World") String name, HttpServletRequest request) {

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            //由于浏览器会把中文直接换成ISO-8859-1编码格式,如果用户在地址打入中文,需要进行如下转换处理
            String tempName = new String(name.getBytes("ISO-8859-1"), "utf-8");

            logger.trace("tempName:" + tempName);
            logger.info(tempName);

            String userName = helloService.processService(tempName);

            map.put("userName", userName);
            
            logger.trace("运行结果:" + map);
            
            helloService = (HelloService) SpringContextUtils.getBean("helloService");
            logger.info(helloService.processService("SpringContextUtils test"));
            
            helloService = (HelloService) SpringBeanFactoryUtils.getBean("helloService");
            logger.info(helloService.processService("SpringBeanFactoryUtils test"));
            
            ServletContext context = request.getServletContext();
            //ServletContext context = request.getSession().getServletContext();
            WebApplicationContext webcontext = (WebApplicationContext)context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
            helloService =  (HelloService) webcontext.getBean("helloService");
            logger.info(helloService.processService("WebApplicationContext test"));
            
            WebApplicationContext webApplication = ContextLoader.getCurrentWebApplicationContext(); 
            helloService = (HelloService) webApplication.getBean("helloService");
            logger.info(helloService.processService("ContextLoader.getCurrentWebApplicationContext() test"));
        } catch (UnsupportedEncodingException e) {
            logger.error("HelloController greeting方法发生UnsupportedEncodingException异常:" + e);
        } catch (Exception e) {
            logger.error("HelloController greeting方法发生Exception异常:" + e);
        }
        return new ModelAndView("/hello", map);
}

        工程完整代码见附件《SpringMVC.zip》。

  • 大小: 19.1 KB
分享到:
评论

相关推荐

    Spring 应用上下文获取 Bean 的常用姿势实例总结

    主要介绍了Spring 应用上下文获取 Bean,结合实例形式总结分析了Spring 应用上下文获取 Bean的实现方法与操作注意事项,需要的朋友可以参考下

    Spring+3.x企业应用开发实战光盘源码(全)

     第4章:讲解如何在Spring配置文件中使用Spring 3.0的Schema格式配置Bean的内容,并对各个配置项的意义进行了深入的说明。  第5章:对Spring容器进行解构,从内部探究Spring容器的体系结构和运行流程。此外,我们...

    JSP 中Spring Bean 的作用域详解

    JSP 中Spring Bean 的作用域详解 Bean元素有一个scope属性,用于定义Bean的作用域,该属性有如下五个值: 1&gt;singleton: 单例模式,在整个spring IOC容器中,单例模式作用域...这种作用域只有在Web应用中使用Spring容

    Spring实战之Bean的作用域request用法分析

    主要介绍了Spring实战之Bean的作用域request用法,结合实例形式分析了spring中Bean的request作用域相关使用技巧与操作注意事项,需要的朋友可以参考下

    Spring.3.x企业应用开发实战(完整版).part2

     《Spring3.x企业应用开发实战》是在《精通Spring2.x——企业应用开发详解》的基础上,经过历时一年的重大调整改版而成的,本书延续了上一版本追求深度,注重原理,不停留在技术表面的写作风格,力求使读者在熟练...

    spring-beans-visualized:可视化的Spring Bean

    可视化的Spring Bean:在运行时查看您的Bean beans端点报告的关于SpringFramework bean的简单图形视图。 在网络浏览器中显示活动bean及其之间的依赖关系。 提供过滤和突出显示豆的功能。 允许更深入地研究您的应用...

    Spring3.x企业应用开发实战(完整版) part1

     《Spring3.x企业应用开发实战》是在《精通Spring2.x——企业应用开发详解》的基础上,经过历时一年的重大调整改版而成的,本书延续了上一版本追求深度,注重原理,不停留在技术表面的写作风格,力求使读者在熟练...

    Spring-Reference_zh_CN(Spring中文参考手册)

    6.8.4. 在Spring应用中使用AspectJ Load-time weaving(LTW) 6.9. 其它资源 7. Spring AOP APIs 7.1. 简介 7.2. Spring中的切入点API 7.2.1. 概念 7.2.2. 切入点实施 7.2.3. AspectJ切入点表达式 7.2.4. 便利的切入...

    Spring中文帮助文档

    6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7. Spring AOP APIs 7.1. 简介 7.2. Spring中的切入点API 7.2.1. 概念 7.2.2. 切入点运算 7.2.3. AspectJ切入点表达式 7.2.4. 便利的切入...

    spring boot实战.pdf高清无水印

    第6章 在Spring Boot中使用Grails 93 6.1 使用GORM进行数据持久化 93 6.2 使用Groovy Server Pages定义视图 98 6.3 结合Spring Boot与Grails 3 100 6.3.1 创建新的Grails项目 100 6.3.2 定义领域模型 ...

    Spring_Framework_ API_5.0.5 (CHM格式)

    Spring 接口中的默认方法 基于 Java8 反射增强的内部代码改进 在框架代码中使用函数式编程 - lambda表达式 和 stream流 4. 响应式编程支持 响应式编程是 SpringFramework5.0 最重要的特性之一。响应式编程...

    Spring攻略(第二版 中文高清版).part1

    3.7 在你的Bean中引入行为 132 3.7.1 问题 132 3.7.2 解决方案 132 3.7.3 工作原理 132 3.8 为你的Bean引入状态 135 3.8.1 问题 135 3.8.2 解决方案 135 3.8.3 工作原理 135 3.9 用基于XML的配置...

    Spring攻略(第二版 中文高清版).part2

    3.7 在你的Bean中引入行为 132 3.7.1 问题 132 3.7.2 解决方案 132 3.7.3 工作原理 132 3.8 为你的Bean引入状态 135 3.8.1 问题 135 3.8.2 解决方案 135 3.8.3 工作原理 135 3.9 用基于XML的配置...

    Spring与iBATIS的集成

    ” &lt;br&gt;但别犯愁:SQL本身具备了一些重要的功能,并且通过模板的使用,在Spring应用中采用iBATIS显得轻而易举。在此摘录中,两位作者将和你一起安装iBATIS并将其集成进你的Spring应用中。他们也阐明了怎样取得你...

    Spring in Action(第二版 中文高清版).part2

    16.4.3 在JSF页面中使用Spring Bean 16.4.4 在JSF中暴露应用程序环境 16.5 Spring中带有DWR的支持Ajax的应用程序 16.5.1 直接Web远程控制 16.5.2 访问Spring管理的Bean DWR 16.6 小结 附录A 装配Spring A.1 ...

    Spring in Action(第二版 中文高清版).part1

    16.4.3 在JSF页面中使用Spring Bean 16.4.4 在JSF中暴露应用程序环境 16.5 Spring中带有DWR的支持Ajax的应用程序 16.5.1 直接Web远程控制 16.5.2 访问Spring管理的Bean DWR 16.6 小结 附录A 装配Spring A.1 ...

    用于获取Spring Bean依赖关系图的工具(高分毕设).zip

    Java SSM项目是一种使用Java语言和SSM框架(Spring + Spring MVC + MyBatis)开发的Web应用程序。SSM是一种常用的Java开发框架组合,它结合了Spring框架、Spring MVC框架和MyBatis框架的优点,能够快速构建可靠、...

    深入解析Spring IoC源码:核心机制与实践应用

    通过精细的分析,本文揭示了AnnotationConfigApplicationContext的实例化过程,详细解读了DefaultListableBeanFactory的作用及其在Bean生产和获取中的关键性作用。同时,本文对Spring Bean的生命周期进行了深入剖析...

    spring杂谈 作者zhang KaiTao

    1.11 在spring中获取代理对象代理的目标对象工具类 1.12 如何为spring代理类设置属性值 1.13 我对SpringDAO层支持的总结 1.14 我对SpringDAO层支持的总结 1.15 我对SpringDAO层支持的总结 1.16 我对Spring 容器管理...

Global site tag (gtag.js) - Google Analytics