首頁 > 軟體

Spring外部化設定的幾種技巧分享

2021-06-21 16:01:21

正文

Envrionment 獲取外部設定

@Log4j2
@SpringBootApplication
public class ConfigurationApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigurationApplication.class, args);
    }
    @Bean
    ApplicationRunner applicationRunner(Environment environment){

        return  args -> {
            log.info("user.name : {}",environment.getProperty("user.name"));
        };
    }
}

修改Spring預設組態檔名稱

啟動程式引數中加入如下設定:

--spring.config.name=app

Value註解設定來源

組態檔

@Bean
ApplicationRunner applicationRunner(Environment environment,
                           @Value("${greeting.message:hello boy}") String message){

   return  args -> {
      log.info("from application.properties user.name : {}",environment.getProperty("user.name"));
      log.info("from application.properties greeting.message : {}",message);

   };
}

預設值

value註解通過冒號來設定預設值:

@Value("${greeting.message:hello boy}")

獲取環境變數值

獲取程式引數值

外部化組態檔優先順序問題

如果有application.properties在springboot 啟動jar包同一目錄,會優先讀取這個檔案中的設定。

Autowire注入ConfigurableEnvrionment

public static void main(String[] args) {

        new SpringApplicationBuilder()
                .sources(ConfigurationApplication.class)
                .run(args);
}

@Autowired
void getConfigurableEnvrionment(ConfigurableEnvironment environment) {
    environment.getPropertySources().addLast(new MyPropertySource());
}

ApplicationInitialiazer 設定

    public static void main(String[] args) {

        new SpringApplicationBuilder()
                .sources(ConfigurationApplication.class)
                .initializers(applicationContext ->
                 applicationContext.getEnvironment().getPropertySources().addLast(new MyPropertySource()))
                .run(args);
    }

static  class  MyPropertySource extends PropertySource<String>{


   public MyPropertySource() {
      super("myproperty");
   }

   @Override
   public Object getProperty(String name) {

      if(name.equalsIgnoreCase("author-name")){
         return  "john";
      }
      return null;
   }
}

然後通過@Value註解注入獲取author-name:

    @Bean
    ApplicationRunner applicationRunner(Environment environment,
                                        @Value("${greeting.message:hello boy}") String message,
                                        @Value("${author-name}") String name){

        return  args -> {
            log.info("from application.properties user.name : {}",environment.getProperty("user.name"));
            log.info("from application.properties author.name : {}",name);
        };
    }

總結

Spring的Environment抽象有很多值得學習的地方,期待下一期每日小技巧。

以上就是Spring外部化設定的幾種技巧分享的詳細內容,更多關於Spring外部化設定的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com