Conf2SystemConfiguration.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package jnpf.config;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.context.ApplicationContextInitializer;
  4. import org.springframework.context.ConfigurableApplicationContext;
  5. import org.springframework.core.Ordered;
  6. import org.springframework.core.env.ConfigurableEnvironment;
  7. import org.springframework.core.env.EnumerablePropertySource;
  8. import org.springframework.core.env.PropertySource;
  9. /**
  10. * 将Spring中的配置设置到系统属性中
  11. * conf2system:
  12. * csp.sentinel.log.dir: log/${spring.application.name}/sentinel
  13. * rocketmq.log.level: "OFF"
  14. * demo.enabled: false
  15. *
  16. * @author JNPF开发平台组
  17. * @version V5.1.0
  18. * @copyright 引迈信息技术有限公司(https://www.jnpfsoft.com)
  19. * @date 2024-12-17
  20. */
  21. @Slf4j
  22. public class Conf2SystemConfiguration implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {
  23. private static final String PREFIX = "conf2system.";
  24. @Override
  25. public void initialize(ConfigurableApplicationContext applicationContext) {
  26. ConfigurableEnvironment environment = applicationContext.getEnvironment();
  27. for (PropertySource<?> source : applicationContext.getEnvironment().getPropertySources()) {
  28. if(source instanceof EnumerablePropertySource){
  29. for (String propertyName : ((EnumerablePropertySource<?>) source).getPropertyNames()) {
  30. if(propertyName.startsWith(PREFIX)){
  31. Object value = environment.getProperty(propertyName);
  32. if(value != null){
  33. System.setProperty(propertyName.substring(PREFIX.length()), String.valueOf(value));
  34. if(log.isDebugEnabled()){
  35. log.debug("Setting system property [{}] to [{}]", propertyName.substring(PREFIX.length()), value);
  36. }
  37. }
  38. }
  39. }
  40. }
  41. }
  42. }
  43. @Override
  44. public int getOrder() {
  45. return Ordered.HIGHEST_PRECEDENCE+1000;
  46. }
  47. }