Sanjay Naik
Sanjay Naik

Reputation: 422

how to load only a particular class which implements Application runner when there are multiple class implementing the same?

In my codebase there are 2 classes which implements org.springframework.boot.ApplicationRunner.When my application gets loaded both the class which implements ApplicationRunner gets loaded.Is there any command line argument with which we can control only specific classes implementing ApplicationRunner gets loaded even though both classes have @Component annotation at class level?

At present i am passing a parameter in command line like

"$SPRINGBOOTAPP_JAVA" -Xmx4096m -jar $BASEDIR/item_substitution-1.0.jar --spring.config.additional-location=${CONFIG_FILE},${CONNECTION_FILE} --applicationRunner="ItemOutOfStockSubstitutionJob"

and in class

@Component public class ItemOutOfStockSubstitutionJob implements ApplicationRunner{

private static final Logger log = LoggerFactory.getLogger(ItemSubstitutionConstants.PROCESS_LOG);

private final String className = getClass().getSimpleName();

@Override

public void run(ApplicationArguments args) throws Exception {

logInfo(log, className +"____________________Item Out Of Stock

SubstitutionJob Process execution starts__________________________");

if( !args.getOptionNames().isEmpty() 

        && 

args.getOptionNames().contains(ItemSubstitutionConstants.APPLICATION_RUNNER

)

        && 

args.getOptionValues(ItemSubstitutionConstants.APPLICATION_RUNNER).get(0).e

qualsIgnoreCase(ItemSubstitutionConstants.ITEM_OUT_OF_STOCK_SUBSTITUTION_JO

B)) {

    logInfo(log, className + "_____________________: 

APPLICATION_RUNNER == ITEM_OUT_OF_STOCK_SUBSTITUTION_JOB

:___________________");

}

logInfo(log, className + "_____________________: APPLICATION_RUNNER 

!= ITEM_OUT_OF_STOCK_SUBSTITUTION_JOB :___________________");

}

}

but because of @Component both classes gets loaded.Is there any way we can

prevent a particular class from not getting loaded from commandline itself?

Upvotes: 0

Views: 502

Answers (1)

viniciusjssouza
viniciusjssouza

Reputation: 1275

One way to switch the implementation at runtime is to provide a factory method which creates the bean. To use it, does NOT annotate the service class with @Component or @Service and, on your @Configuration class, provide a method like this:

@Bean
public ApplicationRunner getApplicationRunner() {
    // read the env var
    // select the desired implementation to be used         
}

This blog post has a nice example about this technique: https://www.intertech.com/Blog/spring-4-conditional-bean-configuration/

Upvotes: 0

Related Questions