静态方法中调用Spring注入的bean对象

直接上代码:

package com.wenzy.config;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import com.hundsun.wudadao.chengdudao.domain.system.SystemConfig;
import com.hundsun.wudadao.chengdudao.service.system.SystemConfigManager;
import com.hundsun.wudadao.chengdudao.service.system.impl.SystemConfigManagerImpl;

public class config implements BeanFactoryAware{
	
	private static BeanFactory      beanFactory;

	private static Map<String,String> systemConfigMap = new HashMap<String,String>();
	
	public static void loadSystemConfigData() {
		System.out.println("come in method2...");
		SystemConfigManager systemConfigManager = (SystemConfigManager) beanFactory.getBean("systemConfigManager",SystemConfigManager.class);//关键的操作
		
		System.out.println("success create bean...");
		List<SystemConfig> configList = systemConfigManager.getAllSystemConfig();
		//遍历数据库中的配置项
		for (SystemConfig systemConfig : configList) {
			//如果状态为关闭,则使用默认值,并加载到缓存中;如果状态为开启,则使用保存的值
			if(systemConfig.getState()==0){
				systemConfigMap.put(systemConfig.getConfigKey(), systemConfig.getConfigDefaultValue());
			}
			else if(systemConfig.getState()==1){
				systemConfigMap.put(systemConfig.getConfigKey(), systemConfig.getConfigValue());
			}
			else{
				continue;
			}
		}
	
	}
	@Override
	public void setBeanFactory(BeanFactory arg0) throws BeansException {
		config.beanFactory = arg0;
		
	}
}
/*SystemConfigManager:是一个已经配置到Spring中的bean,也是作者煞费苦心想调用的对象
* 上诉代码就能实现在任意类使用config.方法
*  关键的几步:
*   1、类实现beanFactoryAware,将类中静态变量beanFactory通过实现的setBeanFactory方法赋值
*   2、在静态类中通过beanFactory.getBean得到Spring容器中的bean(单例),然后转化成我们想要
*      的bean类
*/

猜你喜欢

转载自wenzy-way.iteye.com/blog/2261484