英文:
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<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
@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 { }
英文:
You can autowire ApplicationArguments
bean to read the application arguments that were passed to SpringApplication.run(…)
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 { }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论