Spring boot creates a unified configuration idea

 What is unified configuration of multiple applications in one place? Advantages, changing the database address requires modifying multiple configuration files and restarting everywhere, which is quite troublesome. Using this method, you can make multiple spring boot general configurations in one yaml file, not much nonsense Having said that, let's start the experiment.

 

1. Implement the EnvironmentPostProcessor interface and Ordered. The Ordered interface specifies the startup level, and the EnvironmentPostProcessor interface specifies something to do at startup. The class is as follows:

package com.hks.config;

import java.io.IOException;

import org.slf4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;

public class LoadPropertiesConfig implements EnvironmentPostProcessor, Ordered {
	
	protected static Logger logger = org.slf4j.LoggerFactory.getLogger("LoadPropertiesConfig") ;
	@Override
	public int getOrder() {
		return ConfigFileApplicationListener.DEFAULT_ORDER + 1 ;
	}

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		try {
			YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
			PropertySource<?> load = loader.load("mainyaml",new ClassPathResource("application.yml") , null);
			environment.getPropertySources().addLast( load );
		} catch (IOException e) {
			e.printStackTrace ();
		}
	}

}

 

2. In the maven project, create the file src/main/resources/META-INF/spring.factories. It must be this path. Others will not work. The content of the file is as follows:

org.springframework.boot.env.EnvironmentPostProcessor=com.hks.config.LoadPropertiesConfig

 

This is done, you can write a startup class to see if the startup is successful

package com.hks.epc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication( scanBasePackages = "com.hks")
public class App {
	
	public static void main(String[] args) {
        
        SpringApplication.run(App.class, args) ;
        
	}
}

 

According to this method, you can configure the configuration file that needs to be loaded in the application.yaml file of each project , obtain the configuration in LoadPropertiesConfig, and load the corresponding configuration file into the project. I hope someone can implement it. 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326918830&siteId=291194637