1. 程式人生 > 程式設計 >詳解springboot設定預設引數Springboot.setDefaultProperties(map)不生效解決

詳解springboot設定預設引數Springboot.setDefaultProperties(map)不生效解決

我們都知道springboot 由於內建tomcat(中介軟體)直接用啟動類就可以啟動了。
而且我們有時想程式碼給程式設定一些預設引數,所以使用方法Springboot.setDefaultProperties(map)

SpringApplication application = new SpringApplication(startClass);
//
Map<String,Object> params = new HashMap<>();
params.put("lai.ws.test","test");
application.setDefaultProperties(params);
ApplicationContext context = application.run(startClass,args);

於是啟動後發現 lai.ws.test 居然是null,也就是引數設定不成功,百思不得其解。為此還斷點進入SpringApplication 的原始碼裡。最後發現以下原始碼

  /**
   * Static helper that can be used to run a {@link SpringApplication} from the
   * specified sources using default settings and user supplied arguments.
   * @param primarySources the primary sources to load
   * @param args the application arguments (usually passed from a Java main method)
   * @return the running {@link ApplicationContext}
   */
  public static ConfigurableApplicationContext run(Class<?>[] primarySources,String[] args) {
    return new SpringApplication(primarySources).run(args);
  }

各位,發現了沒,又new 了一個SpringApplication。到此,問題答案找到了。
如果啟動類要設定預設引數,不用使用以下方法去啟動

ApplicationContext context = application.run(startClass,args);

應該使用以下

ApplicationContext context = application.run(args);

到此這篇關於詳解springboot設定預設引數Springboot.setDefaultProperties(map)不生效解決的文章就介紹到這了,更多相關Springboot.setDefaultProperties 不生效內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!