简体   繁体   English

如何通过varargs(程序参数)条件排除Spring bean?

[英]How to exclude Spring beans by varargs (program arguments) conditional?

How can I let spring evaluate varargs and run beans conditionally?如何让 spring 评估varargs并有条件地运行 bean?

@SpringBootConfiguration
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class);
  }
}

@Service
@Order(1) //run if no vararg is given
public class Job1 implements ApplicationRunner {
}

@Service
@Order(2) //TODO run only if a "job2" occurs as vararg
public class Job2 implements ApplicationRunner {
}

Question: I want to start those jobs conditionally by varargs given from command line on application start.问题:我想通过在应用程序启动时从命令行给出的varargs有条件地启动这些作业。 Is that possible?那可能吗?

How about you use @ConditionalOnProperty on those beans and you pass the property to include/exclude them from the command line?您如何在这些 bean 上使用@ConditionalOnProperty并传递属性以从命令行包含/排除它们?

A full example could be:一个完整的例子可能是:

@Service
@Order(1) //run if no vararg is given
@ConditionalOnProperty(name = "my.property", havingValue = "job1")
public class Job1 implements ApplicationRunner {
}

@Service
@Order(2) //TODO run only if a "job2" occurs as vararg
@ConditionalOnProperty(name = "my.property", havingValue = "job2")
public class Job2 implements ApplicationRunner {
}

and then you pass the property with:然后你通过以下方式传递属性:

mvn spring-boot:run -Dspring-boot.run.arguments="--my.property=job1/job2"

Another option could be removing @Component/@Service from the Job1/Job2 classes and in a configuration class creating a bean like:另一种选择可能是从 Job1/Job2 类中删除 @Component/@Service 并在配置类中创建一个 bean,如:

@Bean
public ApplicationRunner applicatinRunner(ApplicationArguments arguments) throws IOException {
        String commandLineArgument = arguments.getSourceArgs()[0];
        //your logic here to decide which one you want to instantiate
        return new Job1()/Job2();
}

It's possible by simply implementing a custom Condition and evaluating ApplicationArguments .只需实现自定义Condition并评估ApplicationArguments The arguments I was looking for are called non-optional args by Spring:我正在寻找的参数被 Spring 称为非可选参数

class Job2Condition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return context.getBeanFactory()
                .getBean(ApplicationArguments.class)
                .getNonOptionArgs()
                .contains("job2");
    }
}

@Component
@Conditional(Job2Condition.class)
public class Job2 implements ApplicationRunner {
}

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

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