如何以编程方式将附加参数传递给 Spring Boot SpringApplication? [英] How to pass additional parameters to a Spring Boot SpringApplication programatically?

查看:19
本文介绍了如何以编程方式将附加参数传递给 Spring Boot SpringApplication?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能遗漏了一些明显的东西,但我试图弄清楚如何在运行应用程序时以编程方式从 Spring Boot SpringApplication 设置/覆盖属性.

I'm probably missing something obvious, but I am trying to figure out how to set/override properties from a Spring Boot SpringApplication programatically when running the app.

默认情况下,我知道我可以将命令行参数传递给启动应用程序,但我想将 Spring Boot 应用程序嵌入到另一个 java 应用程序中,并从父应用程序中执行.我已将其作为项目的依赖项包含在内.

By default, I know I can pass command line arguments to the boot application, but I want to embed the spring boot application in another java app, and executed from within the parent app. I've included it as a dependency to my project.

在我的 Spring Boot 应用程序中,我有以下内容:

In my Spring Boot application I have the following:

static public main(String [] args){
    SpringApplication app = new SpringApplication(Sync.class);
    app.setWebEnvironment(false);
    app.setShowBanner(false);
    app.run(args);
}

这允许我设置命令行参数,例如 --userName=Eric

This allows me to set command line arguments, such as --userName=Eric etc.

虽然我意识到我可以在技术上以编程方式执行相同的操作并将 --userName=Eric 添加到代码中的 args[] 数组中,但我认为必须有另一种更清晰/更整洁的方式来传递参数/property 到我的 app.但是我似乎在 SpringApplication 中找不到任何其他方法可以让我设置该类型的值.

Although I realize I can technically do the same programmatically and add --userName=Eric to my args[] array in code, I figured there must be another cleaner/neater way to pass an argument/property to my app. But I cannot seem to find any other method in SpringApplication that allows me to set that type of value.

我正在寻找可以让我做如下事情的东西:

I'm looking for something that would allow me to do something like the following:

app.setProperty("username", "Eric");

我是否遗漏了一些明显的东西?

Am I missing something obvious?

推荐答案

当您需要对正在创建的应用程序进行更多控制时,您可以使用 SpringApplicationBuilder,在这种情况下,它的 properties 方法.例如:

When you need more control over the application that you are creating, you can use SpringApplicationBuilder and, in this case, its properties method. For example:

 new SpringApplicationBuilder(Application.class)
            .properties("foo=bar").run(args);

也有采用 PropertiesMap 的变体.

There are also variants that take Properties and Map.

这篇关于如何以编程方式将附加参数传递给 Spring Boot SpringApplication?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆