【问题标题】:Can i configure the Spring MVC application so that when ever i run the application, the controller or any method should be called automatically我可以配置 Spring MVC 应用程序,以便当我运行应用程序时,应该自动调用控制器或任何方法
【发布时间】:2020-10-15 20:29:45
【问题描述】:

我开发了一个带有 rest 控制器的 spring 应用程序,它只有一个 GET 方法。 我可以配置 Spring MVC 应用程序,以便当我运行应用程序时,控制器或任何方法都应该自动调用,而无需从浏览器访问 api(就像独立应用程序一样)

【问题讨论】:

    标签: java spring spring-boot spring-mvc


    【解决方案1】:

    你可以创建一个实现org.springframework.boot.CommandLineRunner接口的bean。

    例如

    @Component
    public class MyRunner implements CommandLineRunner {
    @Override
        public void run(String... args) throws Exception {
            // Do stuff here at startup
        }
    }
    

    由于这是一个常规的 Spring 组件,您可以使用字段或构造函数注入来注入其他 Spring 组件。

    【讨论】:

      【解决方案2】:

      您可以在启动后使用应用程序事件侦听器来完成工作。在您的任何组件中添加此代码:

      @EventListener(ApplicationReadyEvent.class)
      public void init( ApplicationReadyEvent ev ) {
          //after startup
      }
      

      Application Events and Listeners查看更多信息

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多