您的位置:首页 > 移动开发

如何加载和使用配置文件中的自定义实体属性

2017-03-20 20:23 309 查看
如何加载配置文件中的自定义实体属性:

情景:

在实际的项目中,操作赋值数据库中的记录时经常会需要一些常量值,比如插入人的性别字段时候,常会使用如下方式persion.setSex("男")类似"男"这样的硬编码,当代码需要在国外使用时,这个就要按照当地的使用方式修改,比如在美国,不得不将“男”改为“male”这样的硬编码不利于国际化,因此实际的工程经常是将的实体应该采用配置文件加载,当需要修改时候,只需要配置一下配置文件就好了。

举一个例子:

schedule.xml文件中内容如下:

<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEpropertiesSYSTEM"http://java.sun.com/dtd/properties.dtd">
<properties>
   <comment>Properties XML</comment>
   <!-- 接受 -->
   <entrykey="default.proinsid.sj">11111</entry>
   <!-- 审核-->
   <entrykey="default.proinsid.zb">22222</entry>
   <!-- 完成 -->
   <entrykey="default.proinsid.bj">33333</entry>
在类中使用:
myclass.setId(GlobalConfig.getInstance().setStatus("yzt.third.default.proinsid.sj"));
那么如何才能加载实体呢?过程如下:
1. ClassPathXmlApplicationContext的使用

ClassPathXmlApplicationContext是spring读取xml最常用的类。而我们一般操作的是其接口ApplicationContext。BeanFactory和ApplicationContext区别不大,BeanFactory不在自动 BeanPostProcessor 和自动 BeanFactoryPostProcessor 上注册。尽量用ApplicationContext。

<!--通配符使用不了解的道友可以参考http://blog.csdn.net/wu020708/article/details/60465050-->

packagecom.iflytek.sgy.schedule;
 
importorg.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.schedule.util.GlobalConfig;
 
/**
 * 入口
 *代码介绍:下代码拷贝自一个工程,用途是加载配置文件
 *
 */
public class App {
  
   public static void main(String[] args) {
      String applicationXml =
"classpath*:spring_schedule/application/application.xml";
      String beanXml =
"classpath*:spring_schedule/bean/schdule.xml";
 
      // job 任务
      String dsJob =
"classpath*:spring_schedule/triggers/TaskJob.xml";
 
      String[] path = {
applicationXml, beanXml,dsJob,
           "classpath*:spring_schedule/trigger.xml",
           "classpath*:spring_schedule/quartz.xml" };
//trigger.xml 和 quartz.xml为项目中用到的定时任务配置文件,不必理会
      ClassPathXmlApplicationContext
wapp = new ClassPathXmlApplicationContext(path);
      GlobalConfig.init(wapp);
   }
}
 
/**
*配置文件加载器
*使用单例模式
**/

import java.lang.reflect.Method;
import java.util.Properties;
import java.util.Set;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
importorg.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
importorg.springframework.beans.factory.config.PropertyResourceConfigurer;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
importorg.springframework.core.io.support.PropertiesLoaderSupport;

public
class
GlobalConfig {
  private static Logger logger = LoggerFactory
.getLogger(GlobalConfig.class);

   private
static
PropertyPlaceholderConfigurer configure;
 
   private
static
Properties properties =null;
   private
static
String myAppConfig ="{}";
   private
static
String[] path =null;
 
   private
static
GlobalConfig instance =null;
 
   private GlobalConfig(String[]path) {
      // 初始化,配置属性到本地properties中区
      try {
        if (properties ==null) {
           properties =new Properties();
           ClassPathXmlApplicationContext
wapp = new ClassPathXmlApplicationContext(path);
           init(wapp);
        }
      } catch (Exceptione) {
        // 初始化属性读取失败
      }
   }
  
   public
static void
init(ClassPathXmlApplicationContextwapp) {
      try {
        properties =
new
Properties();
        configure = (PropertyPlaceholderConfigurer)wapp
              .getBean("propertyPlaceHolder");
 
        // 通过mergeProperties方法读取所有的配置属性信息
        PropertyResourceConfigurer propertyResourceConfigurer =(PropertyResourceConfigurer)configure;
        Method mergeProperties = PropertiesLoaderSupport.class
              .getDeclaredMethod("mergeProperties");
 
        mergeProperties.setAccessible(true);
        Properties props = (Properties)mergeProperties
              .invoke(propertyResourceConfigurer);
 
        Method convertProperties = PropertyResourceConfigurer.class
              .getDeclaredMethod("convertProperties",Properties.class);
        convertProperties.setAccessible(true);
        convertProperties.invoke(propertyResourceConfigurer,props);
        properties.putAll(props);
        parseAppConfig(properties);
      } catch (Exceptione) {
        // 初始化属性读取失败
        logger.error("Exception:",e);
      }
   }
   private GlobalConfig(){
     
   }
  
   public
static void
initContext(String[]paths) {
      path =
paths;
      getInstance();
   }
 
   public
static
GlobalConfig getInstance() {
      if (instance ==null) {
        instance =
new
GlobalConfig(path);
      }
      return
instance;
   }
 
   public String getString(Stringkey) {
      return
properties.getProperty(key);
   }
 
   public
static
String getAppConfig() {
      return
myAppConfig;
   }
 
}

   // 使用示例
myclass.setId(GlobalConfig.getInstance().setStatus("default.proinsid.sj"));
String

更合理的方式:

实现一个实体类,里面定义静态常量

public
class
CommonConstant {
    public
interface
SYNC_STATUS {
       public
static final
String I ="I";
       public
static final
String U ="U";
       public
static final
String D ="D";
       public
static final
String S ="S";
       public
static final
String SJ ="default.proinsid.sj";
       }
    }

在类中使用:

handleNumber=GlobalConfig.getInstance().getString(CommonConstant.SYNC_STATUS.SJ);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐