您的位置:首页 > 编程语言 > Java开发

spring bean 不使用注入的方式获取的两种方式

2014-11-14 14:32 597 查看

非注入方式取得spring注入bean的util类实现

第一种,我用在webservice接口中。
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
* SpringBean的工具类<br>
* 非注入方式取得spring注入bean的util类实现
* @author langkai
*
*/
public final class SpringBeanUtil implements ApplicationContextAware {

private static ApplicationContext ctx;

/**
* 通过spring配置文件中配置的bean id取得bean对象
* @param id spring bean ID值
* @return spring bean对象
*/
public static Object getBean(String id) {
if (ctx == null) {
throw new NullPointerException("ApplicationContext is null");
}
return ctx.getBean(id);
}

@Override
public void setApplicationContext(ApplicationContext applicationcontext)
throws BeansException {
ctx = applicationcontext;
}

}

实现ApplicationContextAware的Bean,在Bean被初始后,将会被注入ApplicationContext的实例。

applicationContext.xml
<bean class="*.SpringBeanUtil"/>

这样在spring配置文件加载时会自动执行ApplicationContextAware的setApplicationContext方法,将applicationContext对象传递给我们的Util类。

SpringBeanUtil.getBean("myBean");

在某些时候我们不希望通过注入也能取得某些bean时有用。

PS:

Spring 中提供一些Aware相关接口,像是BeanFactoryAware、 ApplicationContextAware、ResourceLoaderAware、ServletContextAware等等,这些 Aware接口的Bean在被初始之后,可以取得一些相对应的资源,例如实现BeanFactoryAware的Bean在初始后,Spring容器将会注入BeanFactory的实例,而实现ApplicationContextAware的Bean,在Bean被初始后,将会被注入 ApplicationContext的实例等等。  

 

  ================================

第二种,就是传统的Application程序使用的了。
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("springConfig_bus.xml");
IMsgBusService client = (IMsgBusService) context.getBean("client");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring bean