java 注解的使用
项目会经常解析properies文件,根据key获得value,下面写一个如何使用注解的方式来获得value
1. AnnotateProperties类:用来获得properties文件的路径
package test;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import AnnotateSrc.AnnotateProperties;import java.util.Properties;public class Test { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { AnnotateProperties annotationProperties = Annotate.class .getAnnotation(AnnotateProperties.class); String propertiesName = annotationProperties.value(); String dir = annotationProperties.key(); System.out.println(dir+propertiesName); File f = new File(dir+"\"+propertiesName); Properties pro = readProperties(f); System.out.println(pro.get("header")); } private static Properties readProperties(File file) throws Exception { BufferedInputStream bis = null; Properties prop = null; try { bis = new BufferedInputStream(new FileInputStream(file)); prop = new NullableProperties(); prop.load(bis); } catch (FileNotFoundException ex1) { throw new Exception(ex1); } catch (SecurityException e) { throw new Exception(e); } catch (Exception ex2) { throw new Exception(ex2); } finally { try { if (bis != null) { bis.close(); } } catch (Exception ex) { } } return prop; } public static class NullableProperties extends Properties { public String getProperty(String key, String defaultValue) { String origin = super.getProperty(key, defaultValue); if (origin != null && origin.trim().length() == 0) { // 空白 return defaultValue; } return origin; } };}