如何访问spring bean中的命令行参数? [英] How to access command line args in a spring bean?
本文介绍了如何访问spring bean中的命令行参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题:如何在弹簧 @Bean
中的启动方法中访问 varargs
,如下面的MyService?
Question: how can I access the varargs
of the startup method inside a spring @Bean
like MyService below?
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@Component
public MyService {
public void run() {
//read varargs
}
}
java -jar [jarfile] [命令行参数]
java -jar [jarfile] [Command Line Arguments]
推荐答案
通过分析spring源代码,spring似乎注册了一个类型为的单例bean ApplicationArguments 的方法
prepareContext
类 SpringApplication
By analyzing spring source code, it seems that spring registers a singleton bean of type ApplicationArguments
in the method prepareContext
of the class SpringApplication
context.getBeanFactory().registerSingleton("springApplicationArguments",
applicationArguments);
所以我认为你可以在你的服务中自动装配这个bean:
So I think you can autowire this bean in your service :
@Component
public MyService {
@Autowired
private ApplicationArguments applicationArguments;
public void run() {
//read varargs
applicationArguments.getSourceArgs();
}
}
这篇关于如何访问spring bean中的命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文