为Spring CommandLineRunner传递构造函数args

时间:2018-08-17 17:33:12

标签: spring spring-boot

我有一个使用类np.std(data)的应用程序,该类实现了Spring myClass

CommanLineRunner
@SpringBootApplication @ComponentScan({ . . . } ) public class myClass implements CommandLineRunner { . . . public myClass() { . . . } public myClass( String anArg ) { . . . } public static void main(String[] args) { SpringApplication application = new SpringApplication( myClass.class ); application.setWebEnvironment( false ); application.run( args ); } @Override public void run(String... args) { . . . } } 方法中的

this绑定到Spring自动构造的run实例。我的问题是,对于此构造,我想使用带有参数的非默认构造函数 并且我想将命令行myClass之一传递给该参数。

如何告诉Spring使用非默认构造函数,以及如何为构造函数参数args提供值?

1 个答案:

答案 0 :(得分:0)

为了能够将其他实例传递给CommandLineRunner,建议将您的应用程序类与CommandLineRunner接口分开。因此,您的主类如下所示:

@SpringBootApplication
public class MyApplication {

public static void main(String[] args) {
    SpringApplication.run(MyApplication .class, args);
}

另一方面,我们应该实例化CommandLineRunner作为组成部分:

@Component
public class MyCommandLineRunner implements CommandLineRunner {

    private MyOtherComponent otherComponent

    @Autowired
    public MyCommandLineRunner(MyOtherComponent otherComponent) {
        this.otherComponent = otherComponent;
    }

    public void run(String... args) {
         otherComponent.setArg(arg[0]);
    }
}

一种更方便的方法是通过向其传递一个lambda函数来创建一个bean:

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

    @Bean
    CommandLineRunner initialize(MyOtherComponent otherComponent) {

        return args -> {
            otherComponent.setArg(arg[0]);
        };
    }
}
相关问题