public static String code = "91";
private Properties exampleOne = new Properties();
@PostConstruct
public void postConstruct() throws IOException {
exampleOne.load(new ClassPathResource("example/exampleOne.properties").getInputStream());
}
if ("A".equals(t)) {
return exampleOne.getProperty(prover, code);
}
....
}
}
工作中遇到通过读取property文件中的字段,选取相应的值 这种需求,理解了其中的方法,还有java自带的property各种方法,特此记录一下。
首先我在其他的类中调用test类的parse(String bankCode, String province, String city),
@PostContruct是spring框架的注解,在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法。postConstruct()把example下的exampleOne.properties加载到exampleOne这个property对象中,实现了一次加载多次使用的目的。所以每次调用parse(String t, String prover) 方法来查找property中的value的时候都是从这个对象中寻找的,不用总是加载exampleOne.properties这个文件。
public static String code = "91";这其实是声明了一个默认的值,在exampleOne.getProperty(prover, code)这里会用到,具体getProperty(prover, code)java源码如下:
//传入string类型的key 和一个默认的值(就是code)
public String getProperty(String key, String defaultValue) {
//如果找到这个key,就取出value
String val = getProperty(key);
//如果这个value是空,就取默认值,否则取value的值
return (val == null) ? defaultValue : val;}
//根据key查找value具体实现的方法
public String getProperty(String key) {
//根据key查找对应的对象,如果是string类型就取string 强转的该值sval,否则取空
Object oval = super.get(key);String sval = (oval instanceof String) ? (String)oval : null;
//如果sval为空且property不为空,取property中的值,否则取sval
return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval;}