如何根据参数创建 Spring Boot Beans

huangapple go评论70阅读模式
英文:

How to create spring boot beans based on parameter

问题

我有一个自定义非Spring的命令行处理我想使用计算出的参数创建一些已配置的Spring Bean

fun main(args: Array<String>) {
    val computed = processArgs(args)
    if (computed.xxx()) {
       runApplication<Main>(*args) // 运行Spring应用
    } else {
      do_something_without_spring(computed)
    }
}

然后我想要一个依赖于`computed`的Bean工厂

@Configuration
class Config {

   @Bean
   fun createBean(computed: ComputedType): BeanType {
      if (computed.xyz()) ...  // 如何在这里传递`computed`?
      // 做一些操作并返回一个Bean
   }
}

你应该如何传递它?只需将其编码为字符串并添加到args中吗?如何在工厂方法中以后访问它?还是有没有办法将Bean注入Spring上下文中?

英文:

I have a custom (non-spring) command line processing and i want to create some spring beans configured using that computed parameters

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

and then i want to have a bean factory that depends on 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? how to access it later in factory method? or is there any way to inject bean into spring context?

答案1

得分: 1

你可以使用自动装配(autowire)来读取传递给SpringApplication.run(…​)的应用程序参数的ApplicationArguments bean。

示例:

@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 { }

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

英文:

You can autowire ApplicationArguments bean to read the application arguments that were passed to SpringApplication.run(…​)

See: 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(&quot;&quot;, args.getSourceArgs()));
        return new B();
    }
}
class B { }

huangapple
  • 本文由 发表于 2020年10月16日 21:54:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64390588.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定