springboot-设置默认参数SpringbootsetDefaultPropertiesmap不生效解决

4次阅读

共计 1029 个字符,预计需要花费 3 分钟才能阅读完成。

咱们都晓得 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);
正文完
 0