业务场景: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" />