001/* 002 * Copyright 2012-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.boot.docs.context; 018 019import java.io.IOException; 020 021import org.springframework.boot.SpringApplication; 022import org.springframework.boot.env.EnvironmentPostProcessor; 023import org.springframework.boot.env.YamlPropertySourceLoader; 024import org.springframework.core.env.ConfigurableEnvironment; 025import org.springframework.core.env.PropertySource; 026import org.springframework.core.io.ClassPathResource; 027import org.springframework.core.io.Resource; 028 029/** 030 * An {@link EnvironmentPostProcessor} example that loads a YAML file. 031 * 032 * @author Stephane Nicoll 033 */ 034// tag::example[] 035public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor { 036 037 private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); 038 039 @Override 040 public void postProcessEnvironment(ConfigurableEnvironment environment, 041 SpringApplication application) { 042 Resource path = new ClassPathResource("com/example/myapp/config.yml"); 043 PropertySource<?> propertySource = loadYaml(path); 044 environment.getPropertySources().addLast(propertySource); 045 } 046 047 private PropertySource<?> loadYaml(Resource path) { 048 if (!path.exists()) { 049 throw new IllegalArgumentException("Resource " + path + " does not exist"); 050 } 051 try { 052 return this.loader.load("custom-resource", path).get(0); 053 } 054 catch (IOException ex) { 055 throw new IllegalStateException( 056 "Failed to load yaml configuration from " + path, ex); 057 } 058 } 059 060} 061// end::example[]