gpt4 book ai didi

java - 在线程中访问 springboot 中的命令行参数

转载 作者:太空宇宙 更新时间:2023-11-04 09:09:43 26 4
gpt4 key购买 nike

我运行我的 Spring Boot 应用程序

mvn spring-boot:run -Dspring-boot.run.arguments="test1, test2, test3"

我的可运行程序中需要这 3 个参数。如何在 Compressor 可运行类中访问它们?它打印 null。

@Configuration
public class MultiThreadConfig {

@Bean
public TaskExecutor taskExecutor() {
return new SimpleAsyncTaskExecutor(); // Or use another one of your liking
}

@Bean
public CommandLineRunner schedulingRunner(TaskExecutor executor) {
return new CommandLineRunner() {
public void run(String[] args) throws Exception {
executor.execute(new Compressor(args));
}
};
}
}



public class Compressor implements Runnable {

@Autowired
ApplicationArguments appArgs;

String[] args;

// Constructor
public Compressor(String[] args) {
//Initialization of atributes
}

@Override
public void run() {
System.out.println("COMPRESSOR YO");
System.out.println(Arrays.toString(args));
System.out.println(appArgs);
}
}

最佳答案

正如 Jesper 指出的,您正在使用 new 关键字自己创建 Compressor 对象,因此 ApplicationArguments 不会 Autowiring ,因为 Compressor 的此实例不是由 Spring 管理的。解决方案是为Compressor对象创建一个bean,并让Spring管理它。例如:

@Configuration
public class MultiThreadConfig {

@Bean
public TaskExecutor taskExecutor() {
return new SimpleAsyncTaskExecutor(); // Or use another one of your liking
}


@Bean
public Compressor compressor(ApplicationArguments applicationArguments) {
return Compressor(applicationArguments);
}

@Bean
public CommandLineRunner schedulingRunner(TaskExecutor executor, Compressor compressor) {
return new CommandLineRunner() {
public void run(String[] args) throws Exception {
executor.execute(compressor);
}
};
}
}

public class Compressor implements Runnable {

private final ApplicationArguments appArgs;
private final String[] args;

@Autowired
public Compressor(ApplicationArguments applicationArguments) {
appArgs = applicationArguments;
args = applicationArguments.getSourceArgs();
}

@Override
public void run() {
System.out.println("COMPRESSOR YO");
System.out.println(Arrays.toString(args));
}
}

请注意,我使用构造函数注入(inject)而不是字段注入(inject),这通常是更好的选择。

如果您不想在配置中创建 bean,您还可以使用 Spring 构造型标记 Compressor:

@Component
public class Compressor implements Runnable {

private final ApplicationArguments appArgs;
private final String[] args;

public Compressor(ApplicationArguments applicationArguments) {
appArgs = applicationArguments;
args = applicationArguments.getSourceArgs();
}
//...
}

并在您的配置中使用它的实例,如上所示:

@Bean
public CommandLineRunner schedulingRunner(TaskExecutor executor, Compressor compressor) {
//...
}

关于java - 在线程中访问 springboot 中的命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59798643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com