Can i configure the Spring MVC application so that when ever i run the application, the controller or any method should be called automatically

huangapple go评论91阅读模式
英文:

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应用程序,其中包含一个仅将具有一个GET方法的rest控制器。
我能否配置Spring MVC应用程序,以便无论何时我运行该应用程序,控制器或任何方法都会自动被调用,而无需从浏览器中访问API(就像独立应用程序一样)?

英文:

I have developed a spring application with rest controller which will have only one GET method.
Can i configure the Spring MVC application so that when ever i run the application, the controller or any method should be called automatically with out hitting the api from browser(Just like stand alone application)

答案1

得分: 2

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

例如:

@Component
public class MyRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        // 在启动时在这里进行操作
    }
}

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

英文:

You can create a bean that implements org.springframework.boot.CommandLineRunner interface.

E.g.

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

As this is a regular Spring component, you can use field or constructor injection to inject other Spring components.

答案2

得分: 2

你可以使用应用程序事件监听器在启动后执行工作。将以下代码添加到您的任何组件中:

@EventListener(ApplicationReadyEvent.class)
public void init(ApplicationReadyEvent ev) {
    // 启动后的操作
}

更多信息请参见Application Events and Listeners(应用程序事件和监听器)

英文:

You can use an application event listener to do work after startup. Add this code in any of your components:

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

See more at Application Events and Listeners

huangapple
  • 本文由 发表于 2020年10月15日 20:11:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64371317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定