在项目中总会留一些配置项让用户根据需求修改,这时候就需要一个外部配置文件,同时我们可以在项目中放置一个默认配置文件。主要是通过继承spring提供的PropertyPlaceholderConfigurer这个类来实现的。具体的加载过程请参考如下代码
@Component @Conditional(XXXCondition.class) //根据条件选择是否加载这个component public class EmbeddedPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private String outterProp; String innerProp="xxxx.properties"; Properties configProps; @Override protected void loadProperties(Properties props) throws IOException { if (configProps == null) { init(); } props.putAll(configProps); } private void init() { InputStream innerStream=this.getClass().getClassLoader().getResourceAsStream(innerProp); String content = readContent(innerStream); addContent(content); outterProp=System.getenv("resource_path"); if(outterProp==null){ logger.error("The path to the properties file, "resource_path", is not specified"); return; } Path outterPath = Paths.get(outterProp); try (InputStream outterStream= Files.newInputStream(outterPath)){ content = readContent(outterStream); addContent(content); } catch (IOException e) { logger.error(e.getMessage()); } } private void addContent(String content){ if (content == null || content.length() <= 0) { return; } String[] ss = content.split(" "); for(String s : ss) { if (s == null || s.length() <= 0) { continue; } String[] split = s.split("=",2); String key = split[0]; if (key != null) { key = key.trim(); } if (key == null || key.length() <= 0 || key.charAt(0) == '#') { continue; } String value = split[1]; if (value != null) { value = value.trim(); } if (this.configProps == null) { this.configProps = new Properties(); } this.configProps.put(key, value); } } public static String readContent(InputStream inputStream) { String encoding = "UTF-8"; StringBuffer buffer = new StringBuffer(""); try { InputStreamReader read = new InputStreamReader(inputStream, encoding); BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { buffer.append(lineTxt).append(" "); } read.close(); } catch (Throwable t) { logger.error("error when read content", t); } return buffer.toString(); }
/**
* 可以继承spring提供的Condition接口,根据自定义条件来判断是否加载当前的component
* 例如本例中当环境变量embedded存在且为true的时候才会加载
*/
public class XXXCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return (conditionContext.getEnvironment().getProperty("embedded")!=null&&conditionContext.getEnvironment().getProperty("embedded").contains("true")); } }