有没有一种方法可以根据Spring Boot中的命令行参数注入特定的接口实现?
我有一个数据加载应用程序,根据命令行参数,我需要加载特定类型的数据。
下面是我的主类和CommandLineRunner
@SpringBootApplication
public class DataLoadersApplication implements CommandLineRunner {
private Type1LoadProcess type1LoadProcess;
private Type2LoadProcess type2LoadProcess;
public DataLoadersApplication(Type1LoadProcess type1LoadProcess,
Type2LoadProcess type2LoadProcess) {
this.type1LoadProcess = type1LoadProcess;
this.type2LoadProcess = type2LoadProcess;
}
public static void main(String[] args) {
SpringApplication.run(DataLoadersApplication.class, args);
}
@Override
public void run(String... args) {
if (args[0].equalsIgnoreCase("load-type1")) {
type1LoadProcess.process();
} else if (args[0].equalsIgnoreCase("load-type2")) {
type2LoadProcess.process();
}
}
}有没有办法让我用两个实现Type1DataLoadProcess和Type2DataLoadProcess创建一个DataLoadeProcess接口,并基于命令行参数将实现注入到主类中?
发布于 2018-08-16 21:33:57
一个完整的例子是
@SpringBootApplication
public class DataLoadersApplication implements CommandLineRunner {
public interface LoadProcess {
void doLoad();
}
@Component // default that exists unconditionally in any profile
static class Type1LoadProcess implements LoadProcess {
@Override public void doLoad() { System.out.println("Load1"); }
}
@Profile("type2") // this only exists in the type2 profile
@Primary // if it exists it gets picked over others
@Component
static class Type2LoadProcess implements LoadProcess {
@Override public void doLoad() { System.out.println("Load2"); }
}
// need a 3rd? @Profile("type3") @Primary @Component
@Autowired // need one of them here
private LoadProcess loadProcess;
@Override
public void run(String... args) {
loadProcess.doLoad();
}
public static void main(String[] args) {
SpringApplication.run(DataLoadersApplication.class, args);
}
}这利用了概要文件,并使用主bean机制在没有指定概要文件的情况下允许默认实现。
然后,您可以通过https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html中列出的任何选项来选择要使用的配置文件,例如,通过设置环境变量
SPRING_PROFILES_ACTIVE=type2 java -jar myApp.jar使用属性
java -Dspring.profiles.active=type2 java -jar myApp.jar甚至是一个参数
java -jar myApp.jar --spring.profiles.active=type2当您需要type2实现时。您仍然可以将"type1“设置为活动配置文件,即使它没有定义。它仍然会做正确的事情,并使用type1代码,因为这是默认的。
发布于 2018-08-16 21:14:52
您可以使用Spring profile来实现您的目标:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html
创建接口DataLoadProcess
然后是类:
@Component
@Profile("type1")
public class Type1LoadProcess implements DataLoadProcess {
}
@Component
@Profile("type2")
public class Type2LoadProcess implements DataLoadProcess {
}然后,您可以像这样注入接口类型:
@Autowired
DataLoadProcess dataLoadProcessor;现在,您可以使用其中一个配置文件启动您的应用程序,例如,使用系统属性集:
-Dspring.profiles.active=type1发布于 2018-08-16 21:08:53
为此,我会使用Spring profiles。只需将您的实现转换为Spring Bean,然后基于活动配置文件加载所需的Bean。
然后,当您在启动应用程序时将活动配置文件指定为命令行参数时,应该使用相应的Bean。
https://stackoverflow.com/questions/51877585
复制相似问题