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

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

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

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


当前回答

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

其他回答

在Spring Boot应用程序启动后执行代码块的最佳方法是使用PostConstruct注释。或者你也可以使用命令行运行器。

1. 使用PostConstruct注释

@Configuration
public class InitialDataConfiguration {

    @PostConstruct
    public void postConstruct() {
        System.out.println("Started after Spring boot application !");
    }

}

2. 使用命令行运行器bean

@Configuration
public class InitialDataConfiguration {

    @Bean
    CommandLineRunner runner() {
        return args -> {
            System.out.println("CommandLineRunner running in the UnsplashApplication class...");
        };
    }
}

在春季> 4.1中使用SmartInitializingSingleton bean

@Bean
public SmartInitializingSingleton importProcessor() {
    return () -> {
        doStuff();
    };

}

作为备选方案,CommandLineRunner bean可以实现,也可以使用@PostConstruct注释bean方法。

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

@Component
public class Monitor {
    @Autowired private SomeService service

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

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

为Dave Syer的回答提供了一个例子,这就像一个魅力:

@Component
public class CommandLineAppStartupRunner implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(CommandLineAppStartupRunner.class);

    @Override
    public void run(String...args) throws Exception {
        logger.info("Application started with command-line arguments: {} . \n To kill this application, press Ctrl + C.", Arrays.toString(args));
    }
}

如果你的意思是在应用程序启动后运行一次peace of code,你可以如下所示使用CommandLineRunner:

@SpringBootApplication
public class SpringBootApplication 
  implements CommandLineRunner {

private static Logger LOG = LoggerFactory
  .getLogger(SpringBootConsoleApplication.class);

public static void main(String[] args) {
    LOG.info("STARTING THE APPLICATION");
    SpringApplication.run(SpringBootConsoleApplication.class, args);
    LOG.info("APPLICATION FINISHED");
}

@Override
public void run(String... args) {
    // enter code you want to run after app loaded here
    LOG.info("EXECUTING : command line runner");

    for (int i = 0; i < args.length; ++i) {
        LOG.info("args[{}]: {}", i, args[i]);
    }
}

}

否则,您可以使用DevTools依赖项,它可以帮助您在不手动重新启动应用程序的情况下运行新代码。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
</dependencies>

不要忘记将这些代码添加到pom.xml中,以避免版本警告:

   <properties>
        <java.version>17</java.version>
        <spring-cloud.version>2021.0.3</spring-cloud.version>
    </properties>

 <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>

如果这对你有帮助,给它一个重击!