如何以编程方式强制导入/加载休息控制器

时间:2017-03-13 11:03:30

标签: java spring rest spring-boot

我正在启动一个spring boot rest服务,可能会根据分发情况加载不同的包。这意味着有时分发将包含一些某些REST控制器所在的jar,有时这些控制器不存在。

那么我怎么能告诉spring-boot在哪里找到带有配置文件的控制器。现在我通过注释发送此信息,迫使我为每个发行版创建一个“主要”。我想定义一个唯一的main来导入文件中定义的控制器。换句话说,我想手动访问@Import注释,如下图所示:

@Configuration
@PropertySource("conf.cfg")
@Import(value = {RestContorller1.class,  RestContorller2.class})
@EnableAutoConfiguration
@ConfigurationProperties
@SpringBootApplication
@RestController
@EnableSwagger2
public class Application {

    public static void main(String[] args) {

        String confFile = Const.DEFAULT_CONFIGURATION_FILE;

        if(args.length>0)
            confFile= args[0];
        System.setProperty("spring.config.name",confFile);
        Boolean hasStarted = DataProcessingCore.start(confFile);
        if(hasStarted) {
            SpringApplication springApp =  new SpringApplication(Application.class);
            try {
                springApp.setDefaultProperties(Utils.createPropertyFiles(confFile));

            } catch (IOException e) {
                e.printStackTrace();
            }
            springApp.addInitializers();
            springApp.run(args);


        }

    }
}

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您的控制器将驻留在由maven / gradle导入到您的主项目的JAR中。

为了像Spring引导一样创建auto-configuration,当jar在classpath中时,可以用相同的方式导入控制器,你可以告诉spring找到你的自定义configuration在启动时。

我在这里写了一个简单的例子:Creating your own auto-configuration

在pricipal中,您创建了一个spring-boot应用程序(没有spring boot maven插件!!对于类路径和打包很重要)。并创建一个名为spring.factories的文件(您可以在我链接的指南中找到实际内容),该文件告诉任何具有此jar的spring-boot应用程序加载您的配置,可以执行@ComponentScan搜索您的控制器或手动设置@Bean

这样做,你不必做@Import,动态加载控制器。