【问题标题】:How to force the import/loading of rest controller programatically如何以编程方式强制导入/加载休息控制器
【发布时间】:2017-03-13 11:03:29
【问题描述】:

我正在启动一个 Spring Boot Rest 服务,该服务可能会根据发行版加载不同的包。这意味着有时分发会包含某些 REST 控制器所在的 jar,有时这些控制器不存在。

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

@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);


        }

    }
}

【问题讨论】:

    标签: java spring rest spring-boot


    【解决方案1】:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多