java Spring Boot:在@Bean 注释方法中获取命令行参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39269831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Boot: get command line argument within @Bean annotated method
提问by Taras Velykyy
I'm building a Spring Boot application and need to read command line argument within method annotated with @Bean. See sample code:
我正在构建一个 Spring Boot 应用程序,需要在用 @Bean 注释的方法中读取命令行参数。见示例代码:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public SomeService getSomeService() throws IOException {
return new SomeService(commandLineArgument);
}
}
How can I solve my issue?
我该如何解决我的问题?
采纳答案by freakman
try
尝试
@Bean
public SomeService getSomeService(@Value("${property.key}") String key) throws IOException {
return new SomeService(key);
}
回答by Will Humphreys
@Bean
public SomeService getSomeService(
@Value("${cmdLineArgument}") String argumentValue) {
return new SomeService(argumentValue);
}
To execute use java -jar myCode.jar --cmdLineArgument=helloWorldValue
执行使用 java -jar myCode.jar --cmdLineArgument=helloWorldValue
回答by exoddus
If you run your app like this:
如果你像这样运行你的应用程序:
$ java -jar -Dmyproperty=blabla myapp.jar
or
或者
$ gradle bootRun -Dmyproperty=blabla
Then you can access this way:
然后你可以通过这种方式访问:
@Bean
public SomeService getSomeService() throws IOException {
return new SomeService(System.getProperty("myproperty"));
}
回答by Sourabh Kanojiya
you can run your app like this:
你可以像这样运行你的应用程序:
$ java -server -Dmyproperty=blabla -jar myapp.jar
$ java -server -Dmyproperty=blabla -jar myapp.jar
and can access the value of this system property in the code.
并且可以在代码中访问这个系统属性的值。