java - 如何基于命令行参数加载 Spring 配置?
问题描述
我有几个不同的@Configuration 类,每个类对应一个不同的 Spring Batch 作业,即每个配置中存在一个 Job bean,并且给定作业所需的每个 Step、Tasklet 等都存在于相同的配置类中工作。例子:
@Configuration
public class DemoJobConfiguration(JobBuilderFactory jobBuilderFactory) {
@Bean
public Job demoJob() {
return jobBuilderFactory.get("demoJob").start(...).build();
}
}
@Configuration
public class TestJobConfiguration(JobBuilderFactory jobBuilderFactory) {
@Bean
public Job testJob() {
return jobBuilderFactory.get("testJob").start(...).build();
}
}
该应用程序是一个命令行应用程序。第一个参数是要运行的作业的名称。根据该参数检索关联的 Job bean,然后使用 JobLauncher 执行。例子:
@Override
public void run(String... args) throws Exception {
String jobName = args[0];
Job job = prepareJob(jobName); //gets the Job from the application context
JobParameters jobParameters = prepareJobParameters(args); //sets args[1], etc. to JobParameter objects
JobExecution result = jobLauncher.run(job, jobParameters);
}
我想知道的是,如果 args[0] 是某个值,是否有办法使用 @Conditional 注释(或其他东西)仅加载配置类,例如,
@Configuration
@Conditional("\"testJob\".equals(args[0])")
public class TestJobConfiguration(JobBuilderFactory jobBuilderFactory) {
...
}
这样做的好处是,只有与正在运行的作业相关的 bean 才会被加载到内存中,而与其他作业相对应的 bean 永远不会被加载。随着更多工作被添加到项目中,这将非常有帮助。
是否可以基于命令行参数加载配置?以前做过吗?一个小时的谷歌搜索没有出现任何结果,但我仍然希望有办法做到这一点。
解决方案
我想出了自己问题的答案。
解决方案:
以 --jobName=testJob 的形式包含命令行参数。Spring boot 会自动将其加载到环境中(https://docs.spring.io/spring-boot/docs/1.0.1.RELEASE/reference/html/boot-features-external-config.html)
像这样使用@ConditonalOnProperty 注释:
@ConditionalOnProperty(value = "jobName", havingValue = "testJob") 公共类 TestJobConfiguration { ... }
推荐阅读
- microservices - 如何在 Istio 中记录请求和响应正文
- java - 提供给 orElse() 的方法不完全执行
- laravel - Laravel 工厂无法保存关系
- javascript - 尽管超时会出现 Div
- java - centos上的liquibase安装,JNI错误
- ssl - - IOException AMC java.security.cert.CertificateException:找不到与 api.mitel-amc.com 匹配的主题备用 DNS 名称
- javascript - 引导下拉多选 Onchange 不起作用
- javascript - UTF-8 编码在飞碟中不起作用
- c# - C# DateTime toString 在 Windows Server 2012 和 2016 上的行为不同
- python - numpy - 多维布尔掩码