如何访问spring bean中的命令行参数?

时间:2017-05-09 08:53:47

标签: java spring

问题:如何在varargs弹出{@ 1}}下面的MyService中访问启动方法的@Bean

@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] [命令行参数]

3 个答案:

答案 0 :(得分:9)

通过分析spring源代码,spring似乎在类ApplicationArguments的方法prepareContext中注册了SpringApplication类型的单例bean

context.getBeanFactory().registerSingleton("springApplicationArguments",
            applicationArguments);

所以我认为你可以在你的服务中自动装配这个bean:

@Component
public MyService {

      @Autowired
      private ApplicationArguments  applicationArguments;

      public void run() {
             //read varargs
             applicationArguments.getSourceArgs();

      }
}

答案 1 :(得分:3)

感谢@pvpkiran的提示:

@Component
public class CommandLineHolder implements CommandLineRunner {
    private String[] args;

    @Override
    public void run(String... args) throws Exception {
        this.args = args;
    }

    public String[] getArgs() {
        return args;
    }
}

答案 2 :(得分:0)

@配置 公共类CheckArguments {

private ApplicationArguments applicationArguments;

CheckArguments(ApplicationArguments applicationArguments) {
    this.applicationArguments = applicationArguments;
}

public void printArguments(){
    for(String arg : applicationArguments.getSourceArgs()){
        System.out.println(arg);
    }
}

}