我想在spring-boot应用程序开始监视目录更改之后运行代码。

我已经尝试运行一个新线程,但@Autowired服务还没有设置在那一点。

我已经能够找到ApplicationPreparedEvent,它在@Autowired注释设置之前触发。理想情况下,我希望事件在应用程序准备好处理http请求时触发。

是否有更好的事件可以使用,或者在应用程序在spring-boot中激活后运行代码的更好方法?


当前回答

Spring引导提供了一个带有run()方法的ApplicationRunner接口,在应用程序启动时调用该方法。 但是,我们有一个ApplicationArguments类的实例,而不是传递给回调方法的原始String参数。

@Component
public class AppStartupRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //some logic here
    }
}

其他回答

Try:

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {

    @SuppressWarnings("resource")
    public static void main(final String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);

        context.getBean(Table.class).fillWithTestdata(); // <-- here
    }
}

使用CommandLineRunner或ApplicationRunner的最佳方式 两者之间唯一的区别是run()方法 CommandLineRunner接受字符串数组,ApplicationRunner接受应用参数。

我非常喜欢@cahen (https://stackoverflow.com/a/44923402/9122660)对EventListener注释的使用建议,因为它非常干净。不幸的是,我不能让它在Spring + Kotlin设置中工作。对Kotlin有效的方法是将类作为方法参数添加:

@EventListener 
fun doSomethingAfterStartup(event: ApplicationReadyEvent) {
    System.out.println("hello world, I have just started up");
}

为什么不创建一个bean,在初始化时启动监视器呢?

@Component
public class Monitor {
    @Autowired private SomeService service

    @PostConstruct
    public void init(){
        // start your monitoring in here
    }
}

在为bean完成任何自动装配之前,不会调用init方法。

其实很简单:

@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
    System.out.println("hello world, I have just started up");
}

在1.5.1.RELEASE版本上测试