Spring 引导:获取@Bean 注释方法中的命令行参数

Spring Boot: get command line argument within @Bean annotated method

我正在构建一个 Spring 引导应用程序,需要在使用 @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("${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 -Dmy属性=blabla -jar myapp.jar

并且可以在代码中访问这个系统属性的值。

 @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);
    }
}