当前位置 : 主页 > 编程语言 > java >

Spring获取Bean的工具类

来源:互联网 收集:自由互联 发布时间:2021-06-28
使用工具类获取Spring管理的Bean public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name);} SpringUtil.java /**applicationContext.xml中配置: web.xml中配置: contextConfigLocation
使用工具类获取Spring管理的Bean
public static Object getBean(String name) throws BeansException {
    return applicationContext.getBean(name);
}
SpringUtil.java
/**
applicationContext.xml中配置:
	
 

web.xml中配置:
	
 
	
 
		
  
   contextConfigLocation
  
		
  
   classpath*:/applicationContext*.xml
  
	
 
	
 
	
 
		
  
   org.springframework.web.context.ContextLoaderListener
  
	
 
**/


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

/**
 * Spring容器会自动通过调用ApplicationContextAware接口中的setApplicationContext方法把上下文环境对象注入ApplicationContextAware的实现类中。
 **/
public class SpringUtil implements ApplicationContextAware, DisposableBean {

	public SpringUtil() {
	}

	/** 属性注入: Spring框架应用上下文对象 */
	private static ApplicationContext applicationContext = null;

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

	public void destroy() throws Exception {
		applicationContext = null;
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

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

}

/**
 * Demo: @Service("userServiceImpl") 
 * public class UserServiceImpl implements UserService{}
 * 
 * UserService userService = (UserService)SpringUtil.getBean("userServiceImpl");
 **/
网友评论