我正在创建一个Java应用程序,它根据特定的条件/配置实例化一个SpringBoot应用程序来接收一些HTTP消息.

我的问题是,我有一个ReceiverService,它需要使用一些在SpringBoot应用程序之外创建的变量.Is there a way to pass local java variables (from inside the application, not outside like the shell or files) to SpringBoot components?

示例:

我有一个Manager对象,根据某些条件,它定义了一个变量param,我想在SpringBoot组件ReceiverService中使用它.

public class Manager {

    public Manager(bool condition) {
         String param = "foo";
         if (condition) {
             param = "bar";
         }
         
         ReceiverApp receiver = new ReceiverApp(); // init SpringBoot app
    }
}

SpringBoot应用程序:

@SpringBootApplication
public class ReceiverApp {

    public ReceiverApp() {

        SpringApplication.run(ReceiverApp.class);
    }
@Component
public class ReceiverService implements InitializingBean {

    final CustomObject obj1 = new CustomObject(param);

    @Override
    public void aFunction() throws Exception {
        MyConfig config = MyConfig.build(param);
    }
}

推荐答案

SpringApplication.run被设计为接受key=value对,就像您在Java中的main方法的命令行参数中给出的那样.

由于您的类路径中似乎有另一个Spring boot应用程序jar,并且似乎能够实例化ReceiverApp,因此您可以将参数作为字符串传递(格式为字符串[]{"key1=value1","key2=value2"})

这些可以传递给SpringApplication.运行,这些将自动成为Spring配置值,可以在应用程序中的任何位置注入这些值.

@SpringBootApplication
public class ReceiverApp {

    public ReceiverApp(String[] notReallyFromCommandLineArgs) {

        SpringApplication.run(ReceiverApp.class, notReallyFromCommandLineArgs);
    }

您可以发送如下参数:

String[] params = new String[]{"my.params.param1="+param1};
ReceiverApp receiver = new ReceiverApp(params);

您可以将它们作为值注入到接收器Spring应用程序中的任何位置.

@Value("my.params.param1")
String theParam1;

参考:

Java相关问答推荐

[145007:JC_ILLEGAL_SYMBOL_CHARACTER保存时:griddb中的牧师

java.lang. StackOverFlow错误:显示表及其依赖项时为空

泽西岛:退回到不注射的客户"

使用hibiter中特定字段的where条款自定义映射

int Array Stream System. out. print方法在打印Java8时在末尾添加% sign

如何粘合(合并)文件Lucene?

Quarkus keycloat配置不工作.quarkus. keycloak. policy—enforcer. enable = true在. yaml表示中不工作

使用标记时,场景大纲不在多个线程上运行

@org.springframework.beans.factory.annotation.Autowired(required=true)-注入点有以下注释:-SpringBoot

在Java 17中使用两个十进制数字分析时间时出错,但在Java 8中成功

如何让JVM在SIGSEGV崩溃后快速退出?

Java Mooc.fi Part 12_01.Hideout -返回和删除方法

Sack()步骤中的合并运算符未按预期工作

继续收到错误SQLJDBC EXCEPTION执行";org.springframework.dao.InvalidDataAccessResourceUsageException:&

如何在Cosmos DB(Java SDK)中增加默认响应大小

将ByteBuffer异步写入InputStream或Channel或类似对象

泛型与泛型问题的完美解决方案?

为什么相同的数据条码在视觉上看起来不同?

Java 21内置http客户端固定运营商线程

MapStruct记录到记录的映射不起作用