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

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

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

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


当前回答

“Spring Boot”方式是使用CommandLineRunner。只需添加该类型的bean,就可以了。在Spring 4.1 (Boot 1.2)中,也有一个SmartInitializingBean,它在所有东西初始化后得到一个回调。还有SmartLifecycle(来自Spring 3)。

其他回答

“Spring Boot”方式是使用CommandLineRunner。只需添加该类型的bean,就可以了。在Spring 4.1 (Boot 1.2)中,也有一个SmartInitializingBean,它在所有东西初始化后得到一个回调。还有SmartLifecycle(来自Spring 3)。

您可以使用ApplicationRunner扩展类,重写run()方法并在那里添加代码。

import org.springframework.boot.ApplicationRunner;

@Component
public class ServerInitializer implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {

        //code goes here

    }
}

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

@Component
public class AppStartupRunner implements ApplicationRunner {

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

你可以使用@Component

@RequiredArgsConstructor
@Component
@Slf4j
public class BeerLoader implements CommandLineRunner {
    //declare 

    @Override
    public void run(String... args) throws Exception {
        //some code here 

    }

你试过ApplicationReadyEvent吗?

@Component
public class ApplicationStartup 
implements ApplicationListener<ApplicationReadyEvent> {

  /**
   * This event is executed as late as conceivably possible to indicate that 
   * the application is ready to service requests.
   */
  @Override
  public void onApplicationEvent(final ApplicationReadyEvent event) {

    // here your code ...

    return;
  }
}

代码来自:http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/

下面是文档中提到的启动事件:

... Application events are sent in the following order, as your application runs: An ApplicationStartedEvent is sent at the start of a run, but before any processing except the registration of listeners and initializers. An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known, but before the context is created. An ApplicationPreparedEvent is sent just before the refresh is started, but after bean definitions have been loaded. An ApplicationReadyEvent is sent after the refresh and any related callbacks have been processed to indicate the application is ready to service requests. An ApplicationFailedEvent is sent if there is an exception on startup. ...