Spring 获取配置文件中注入的Bean对象

业务场景:Config类中,需要获取其它位置的配置文件的参数。用户可以在xml配置文件修改其位置,可以是绝对路径或者相对路径;

1、ApplicationContextHelper  继承ApplicationContextAware,用来获取已注入的bean对象

package hk.emc.rrs.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextHelper implements ApplicationContextAware {
    private static ApplicationContext appCtx;
    @Override
    public void setApplicationContext( ApplicationContext applicationContext ) throws BeansException {
        appCtx = applicationContext;
    }
    public static Object getBean( String beanName ) {

        return appCtx.getBean( beanName );
    }
    public static <T> T getBean(Class<T> clz) {

        return (T)appCtx.getBean(clz);
    }
}

2、Config类,提供方法供系统调用以获取配置文件中的配置信息

package hk.emc.rrs.util;

import java.io.IOException;
import java.util.Properties;

import org.springframework.core.io.ClassPathResource;

public class Config{
	private static Properties pro;
	private static String excelTempDirName;
	
	static {
		try {
			System.out.println("Start to read config.properties");
			pro = (Properties) ApplicationContextHelper.getBean("props");
			System.out.println("config:" + pro);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static String getProperty(String key) {
		
		System.out.println("get " + key + " from config.properties");
		if(pro==null){
			try {
				pro = (Properties) ApplicationContextHelper.getBean("props");
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		return pro.getProperty(key);
	}
	
	public static String getExcelDownPath() {
		if (excelTempDirName == null) {
			try {
				String path = new ClassPathResource("hk\\emc\\rrs\\resource\\downloadTemplate\\demo.txt").getFile().getAbsolutePath();
				excelTempDirName = path.substring(0, path.length() - 8);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return excelTempDirName;
	}

	

}

3、配置文件注入,可以是dispatcher-servlet.xml,注意配置Bean的位置,一定要在component-scan之前,这里存在加载先后的问题。

<bean id="applicationContextHelper" class="hk.emc.rrs.util.ApplicationContextHelper"></bean>
	<!-- config path eg:file:G:/work/RRW_DEV/config.properties-->
	<bean id="props"
		class="org.springframework.beans.factory.config.PropertiesFactoryBean">
		<!--<property name="location" value="file:G:/work/RRW_DEV/config.properties" />  -->
		<property name="location" value="classpath:config.properties" />
	</bean>
	<context:component-scan base-package="hk.emc.rrs" />

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值