describe
在项目启动的过程中执行一些指定的业务逻辑代码,初始化数据,加载某一个配置文件等等,所有在项目启动过程中需要自动执行的业务。
Scenes
Here are a few scenarios I encountered during development:
- If the project integrates other services, colleagues need to start the service when starting, for example: Netty service, ftp service construction, and so on.
- Initial configuration is required when the project starts, for example: initializing a certain item of information or preprocessing a certain item of information.
- Project startup needs to interact or read configuration with other systems.
Method 1: Implement the ApplicationRunner interface to rewrite the logic of the run method
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class InitatialConfig implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("项目启动初始化");
}
}
Method 2: Implement the CommandLineRunner interface to rewrite the logic of the run method
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class InitatialConfigCommand implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner:"+"{}"+"接口实现方式重写");
}
}
Method 3: Using the @PostConstruct annotation
@PostConstruct
public void testInitConfig(){
System.out.println("@PostConstruct:"+"{}"+"注解方式实现启动初始化配置");
}
initialization sequence
- @PostConstruct annotation method
- CommandLineRunner interface implementation
- Implementation of the ApplicationRunner interface
Notice:
当CommandLineRunner或者ApplicationRunner存在多个实现类的同时,可以使用@Order(1)注解进行顺序执行,该注解控制Bean的执行顺序。