How can I let spring evaluate varargs
and run beans conditionally?
@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. Is that possible?
How about you use @ConditionalOnProperty
on those beans and you pass the property to include/exclude them from the command line?
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:
@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
. The arguments I was looking for are called non-optional args by 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 {
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.