有没有办法在 Spring Boot 启动 Tomcat 之前运行一个 Controller 来初始化一些数据?
我当前的代码如下所示:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Controller controller = (Controller) context.getBean("controller");
controller.start();
context.close();
SpringApplication.run(Application.class, args);
}
}
@Controller
@Component("controller")
public class Controller {
@Autowired
private Runner runner;
public void start() {
runner.test();
}
}
@Configuration
@PropertySource("classpath:config.properties")
@Component("runner")
public class Runner {
@Value("${name}")
private String name;
public void test() {
System.out.println("hello " + name)
}
public String getName() {
return name;
}
}
@Controller
public class HelloController {
@Autowired
private Runner runner;
@RequestMapping("/hello")
public CalenderCollection data(@PathVariable("name")String name, Model model) {
model.addAttribute("name", runner.getName());
return "hello";
}
}
@Configuration
@ComponentScan(basePackages = "com.test")
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
这会将正确的名称打印到控制台中。但是当我访问 url 时,runner
为空。然后我想把Application和Controller类改成这样:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Controller
@Component("controller")
public class Controller {
@Autowired
private Runner runner;
public Controller() {
runner.test();
}
}
但现在我遇到了 runner
一开始就为 null 的问题。在开始时收集一些数据然后继续该过程的正确方法是什么?
最佳答案
通常您使用 ApplicationRunner
或 CommandLineRunner
在应用程序启动之前运行一些代码。
If you need to run some specific code once the SpringApplication has started, you can implement the ApplicationRunner or CommandLineRunner interfaces. Both interfaces work in the same way and offer a single run method which will be called just before SpringApplication.run(…) completes.
The CommandLineRunner interfaces provides access to application arguments as a simple string array, whereas the ApplicationRunner uses the ApplicationArguments interface discussed above.
import org.springframework.boot.*
import org.springframework.stereotype.*
@Component
public class MyBean implements CommandLineRunner {
public void run(String... args) {
// Do something...
}
}
关于java - 没有请求的Spring Boot运行 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46586373/