从Spring Controller启动CommandLineRunner的方法如下:
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// 在这里编写你的逻辑代码
System.out.println("Hello, CommandLineRunner!");
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
private final MyCommandLineRunner myCommandLineRunner;
@Autowired
public MyController(MyCommandLineRunner myCommandLineRunner) {
this.myCommandLineRunner = myCommandLineRunner;
}
@GetMapping("/start")
public String start() {
// 调用CommandLineRunner的run方法
myCommandLineRunner.run();
return "Started CommandLineRunner";
}
}
/start
接口即可触发CommandLineRunner的run方法。这样,当访问/start
接口时,Spring Controller会调用MyCommandLineRunner的run方法,从而实现从Spring Controller启动CommandLineRunner的功能。
注意:以上代码示例仅为演示目的,实际应用中需要根据具体需求进行逻辑编写和异常处理。
领取专属 10元无门槛券
手把手带您无忧上云