方案一、使用注解( @PostConstruct)
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class AutoStartConsumer {
@PostConstruct
public void TestAutoStart() throws Exception {
//启动就会调用
}
}
方案二、使用启动类(实现CommandLineRunner)
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.CommandLineRunner;
@SpringBootApplication
public class MessageApplication implements CommandLineRunner {
// 启动类主方法(不用动)
public static void main(String[] args) {
SpringApplication.run(MessageApplication.class, args);
}
// 服务启动后自动调用的方法
@Override
public void run(String... args) throws Exception {
//启动就调用
}
}
方案三、使用启动类(实现ApplicationRunner)
@SpringBootApplication
public class MessageApplication implements ApplicationRunner{
// 启动类主方法(不用动)
public static void main(String[] args) {
SpringApplication.run(MessageApplication.class, args);
}
// 服务启动后自动调用的方法
@Override
public void run(String... args) throws Exception {
//启动就调用
}
}
后两个可以加载普通类上但是要交给spring进行管理 多个的话使用@Order注解进行设置启动顺序或者实现Ordered重写getOrder 返回“顺序”就可以指定 越小越先执行