首页 > 解决方案 > 在springboot中加载多个带有注释的springboot应用程序

问题描述

我有一个 springboot 应用程序来根据用户输入动态加载不同的类。

有人可以建议任何更好和优化的方法来做到这一点。

以下是我的方法:-

//I have a map of actions available with their respective classes(which is also a springboot app)
private static Map<String,Class> actions = ImmutableMap.<String,Class>builder()
                                                       .put("A",A.class),
                                                       .put("B",B.class);

//main method of springboot root app
public static void main(String args[]){
 new MainApplication().run(args);
}

//get the action class and run that application
public void run(String args){
 Class action = getAction();
 SpringApplication app = new SpringApplicationBuilder(job).build();
 app.run(args);
}

//action.name is passed as an argument while starting the application( for.ex action.name="A")
private Class getAction(){
 String action = System.getProperty("action.name");
 Class classType = actionMap.get(action);
 return classType;
}

现在我想用一个注释来加载这些动作应用程序。有人可以建议任何方法来做同样的事情。

标签: javaspringspring-bootspring-batch

解决方案


使用条件 Bean 概念如下

@Service
@ConditionalOnProperty(
        value="action.name", 
        havingValue = "a", 
        matchIfMissing = false)
public class TestBeanConditional {

}

推荐阅读