Spring在web应用中获得Bean的方法

一:使用ApplicationContext获得Bean

首先新建一个类,该类必须实现ApplicationContextAware接口,改接口有一个方法,public void setApplicationContext(ApplicationContext applicationContext)throws BeansException ,

也就是说框架会自动调用这个方法返回一个ApplicationContext对象。具体类如下:

SpringContextUtils ApplicationContext applicationContext = null;* 6 * 当继承了ApplicationContextAware类之后,那么程序在调用 7 * getBean(String)的时候会自动调用该方法,不用自己操作setApplicationContext(ApplicationContext applicationContext)throws BeansException {10SpringContextUtils.applicationContext = applicationContext;11 } ApplicationContext getApplicationContext() {13return applicationContext;14 }15/***16 * 根据一个bean的id获取配置文件中相应的bean name BeansExceptionObject getBean(String name) throws BeansException {22return applicationContext.getBean(name);23 }24/***25 * 类似于getBean(String name)只是在参数中提供了需要返回到的类型。 name requiredType BeansExceptionObject getBean(String name, Class requiredType) throws BeansException {32return applicationContext.getBean(name, requiredType);33 }* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true name boolean containsBean(String name) {41return applicationContext.containsBean(name);42 }* 判断以给定名字注册的bean定义是一个singleton还是一个prototype。46 * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException) name boolean NoSuchBeanDefinitionExceptionisSingleton(String name) throws NoSuchBeanDefinitionException {52return applicationContext.isSingleton(name);53 } name Class 注册对象的类型 NoSuchBeanDefinitionExceptionClass getType(String name) throws NoSuchBeanDefinitionException {61return applicationContext.getType(name);62 }* 如果给定的bean名字在bean定义中有别名,则返回这些别名 name NoSuchBeanDefinitionExceptionString[] getAliases(String name) throws NoSuchBeanDefinitionException {71return applicationContext.getAliases(name);72 }73 }

该类中有一个getBean(String name)方法,该方法用applicationContext去获得Bean实例,而applicationContext

是由系统启动时自动设置的。注意,,在applicationContext.xml配置文件中需要把该类加上。<bean/>

二:通过BeanFactory接口获得Bean

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

SpringBeanFactoryUtils implements BeanFactoryAware {BeanFactory beanFactory = null;SpringBeanFactoryUtils factoryUtils = null;setBeanFactory(BeanFactory beanFactory) throws BeansException { 7SpringBeanFactoryUtils.beanFactory = beanFactory; 8 } BeanFactory getBeanFactory() {10return beanFactory;11 } SpringBeanFactoryUtils getInstance(){13if(factoryUtils==null){factoryUtils = new SpringBeanFactoryUtils();16 }17return factoryUtils;18 } Object getBean(String name){20return beanFactory.getBean(name);21 }22 }

人生至少要有两次冲动,一为奋不顾身的爱情,一为说走就走的旅行。

Spring在web应用中获得Bean的方法

相关文章:

你感兴趣的文章:

标签云: