1. 程式人生 > >Spring Boot 02 EnvironmentPostProcessor介面

Spring Boot 02 EnvironmentPostProcessor介面

EnvironmentPostProcessor是Spring Boot的一個拓展介面,我們可以通過這個介面來新增配置檔案。

可以通過http等方式構成一個Properties,實現統一的管理配置檔案。

這裡只是簡單的實現在檔案管理下的配置檔案。

這是原始碼的解釋,說明了該介面的實現類要在classpath:META-INT/spring.factories裡面註冊

Allows for customization of the application's {@link Environment} prior to the
application context being refreshed.
<p>
 EnvironmentPostProcessor implementations have to be registered in
{@code META-INF/spring.factories}, using the fully qualified name of this class as the
 key.
 <p>
 {@code EnvironmentPostProcessor} processors are encouraged to detect whether Spring's
 {@link org.springframework.core.Ordered Ordered} interface has been implemented or if
 the @{@link org.springframework.core.annotation.Order Order} annotation is present and
 to sort instances accordingly if so prior to invocation.

實現類MyEnvironmentPostProcessor
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.stereotype.Component;

@Component
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment,
			SpringApplication application) {
		System.out.println("1");
		Properties properties=null;
		try{
			properties =new Properties();
			properties.load(new FileInputStream("E:/SpringBoot/application1.properties"));
			PropertiesPropertySource  propertySource =new PropertiesPropertySource("ds", properties);
			environment.getPropertySources().addLast(propertySource);
		}
		catch(Exception e){
			e.printStackTrace();
		}
		

	}
}

spring.factories

org.springframework.boot.env.EnvironmentPostProcessor=com.springboot.www.config.MyEnvironmentPostProcessor