步骤如下:
使用CustomEnvironmentPostProcessor实现EnvironmentPostProcessor(Spring框架中的EnvironmentPostProcessor接口允许在Spring应用程序的环境被完全配置之前对其进行自定义处理。)
@Slf4j
public class CustomEnvironmentPostProcessor implements EnvironmentPostProcessor {
private PropertiesPropertySourceLoader loader = new PropertiesPropertySourceLoader();
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
MutablePropertySources propertySources = environment.getPropertySources();
Resource resource = new ClassPathResource("custom.properties");
try {
PropertySource ps = loader.load("xxx", resource)
.get(0);
propertySources.addFirst(ps);
} catch (Exception e) {
log.error("Exception!", e);
}
}
}
然后在resource目录下创建一个custom.properties的配置文件,定义如下:
custom.greeting=hello
简单做一个测试:
@SpringBootApplication
@Slf4j
public class PropertySourceDemoApplication implements ApplicationRunner {
@Value("${custom.greeting}")
private String greeting;
public static void main(String[] args) {
SpringApplication.run(PropertySourceDemoApplication.class, args);
}
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("{}", greeting);
}
}
输出结果如下: