简体   繁体   English

如何根据参数创建spring boot bean

[英]How to create spring boot beans based on parameter

I have a custom (non-spring) command line processing and i want to create some spring beans configured using that computed parameters我有一个自定义(非 spring)命令行处理,我想创建一些使用该计算参数配置的 spring bean

fun main(args: Array<String>) {
        val computed = processArgs(args)
        if (computed.xxx()) {
           runApplication<Main>(*args) // run spring app
        } else {
          do_something_without_spring(computed)
        }
}

and then i want to have a bean factory that depends on computed然后我想要一个依赖于computed的豆工厂

@Configuration
class Config {
 
   @Bean
   fun createBean() {
      if (computed.xyz()) ...  // how to pass `computed` here? 
   }
}

how should i pass it?我该如何通过? just encode it as string and add to args?只是将其编码为字符串并添加到 args? how to access it later in factory method?稍后如何在工厂方法中访问它? or is there any way to inject bean into spring context?或者有什么方法可以将 bean 注入 spring 上下文?

You can autowire ApplicationArguments bean to read the application arguments that were passed to SpringApplication.run(…​)您可以自动装配ApplicationArguments bean 以读取传递给SpringApplication.run(…​)的应用程序参数

See: https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-application-arguments请参阅: https : //docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-application-arguments

Example:例子:

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

@Configuration
class C {
    @Bean
    B b(ApplicationArguments args) {
        System.out.println(String.join("", args.getSourceArgs()));
        return new B();
    }
}
class B { }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM