@PostConstruct
對於注入到Spring容器中的類,在其成員函數前添加@PostConstruct注解,則在執行Spring beans初始化時,就會執行該函數。
但由於該函數執行時,其他Spring beans可能並未初始化完成,因此在該函數中執行的初始化操作應當不依賴於其他Spring beans。
@Component public class Construct { @PostConstruct public void doConstruct() throws Exception { System.out.println("初始化:PostConstruct"); } }
CommandLineRunner
CommandLineRunner
是Spring提供的接口,定義了一個run()方法,用於執行初始化操作。
@Component public class InitCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("初始化:InitCommandLineRunner"); } }
CommandLineRunner的時機為Spring beans初始化之后,因此CommandLineRunner的執行一定是晚於@PostConstruct的。
若有多組初始化操作,則每一組操作都要定義一個CommandLineRunner派生類並實現run()方法。這些操作的執行順序使用@Order(n)來設置,n為int型數據。
@Component @Order(99) public class CommandLineRunnerA implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("初始化:CommandLineRunnerA"); } } @Component @Order(1) public class CommandLineRunnerB implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("初始化:CommandLineRunnerB"); } }
如上,會先執行CommandLineRunnerB
的run(),再執行CommandLineRunnerA
的run()。@Order(n)
中的n較小的會先執行,較大的后執行。n只要是int值即可,無需順序遞增。
ApplicationRunner
ApplicationRunner
接口與CommandLineRunner
接口類似,都需要實現run()方法。二者的區別在於run()方法的參數不同:
@Component public class InitApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments applicationArguments) throws Exception { System.out.println("初始化:InitApplicationRunner"); } }
ApplicationRunner接口的run()參數為ApplicationArguments對象,因此可以獲取更多項目相關的內容。
ApplicationRunner接口與CommandLineRunner接口的調用時機也是相同的,都是Spring beans初始化之后。因此ApplicationRunner接口也使用@Order(n)來設置執行順序。