[英]Spring Boot: get command line argument within @Bean annotated method
我正在構建一個 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);
}
}
我該如何解決我的問題?
@Bean
public SomeService getSomeService(
@Value("${cmdLineArgument}") String argumentValue) {
return new SomeService(argumentValue);
}
執行使用java -jar myCode.jar --cmdLineArgument=helloWorldValue
您還可以將ApplicationArguments
直接注入您的 bean 定義方法並從中訪問命令行參數:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public SomeService getSomeService(ApplicationArguments arguments) throws IOException {
String commandLineArgument = arguments.getSourceArgs()[0]; //access the arguments, perform the validation
return new SomeService(commandLineArgument);
}
}
試試
@Bean
public SomeService getSomeService(@Value("${property.key}") String key) throws IOException {
return new SomeService(key);
}
如果你像這樣運行你的應用程序:
$ java -jar -Dmyproperty=blabla myapp.jar
或
$ gradle bootRun -Dmyproperty=blabla
然后你可以通過這種方式訪問:
@Bean
public SomeService getSomeService() throws IOException {
return new SomeService(System.getProperty("myproperty"));
}
你可以像這樣運行你的應用程序:
$ java -server -Dmyproperty=blabla -jar myapp.jar
並且可以在代碼中訪問這個系統屬性的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.