参考原文:https://www.cnblogs.com/zuidongfeng/p/9926471.html
方式1:implements ApplicationRunner
import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component public class ApplicationRunnerImpl implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("通过实现ApplicationRunner接口,在spring boot项目启动后打印参数"); String[] sourceArgs = args.getSourceArgs(); for (String arg : sourceArgs) { System.out.print(arg + " "); } System.out.println(); } }
方式2:implements CommandLineRunner
spring容器加载完自动监听
第1步,实现springboot默认的监听接口,该方法在spring容器加载完自动监听
import com.sinosoft.speech.swing.Main; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; /** * spring boot 容器加载后自动监听 */ @Component public class MyCommandRunner implements CommandLineRunner { @Override public void run(String... args) { System.out.println("开始启动1个页面"); try { Runtime.getRuntime().exec("cmd /c start http://localhost:8080/index"); } catch (Exception ex) { ex.printStackTrace(); } } }
2.正常启动就行
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author lijunming * @date 2018/7/22 下午2:40 */ @SpringBootApplication public class SpeechApplication { public static void main(String[] args) { SpringApplication.run(SpeechApplication.class, args); } }
配置完后,运行springboot启动类,就会自动打开1个浏览器访问项目的html5页面,
方式 3 : 实现ServletContextAware接口并重写其setServletContext方法
import org.springframework.stereotype.Component; import org.springframework.web.context.ServletContextAware; import javax.servlet.ServletContext; @Component public class DemoServletContextAware implements ServletContextAware { // 该方法会在填充完普通Bean的属性,但是还没有进行Bean的初始化之前执行 @Override public void setServletContext(ServletContext servletContext) { System.out.println("------------>>>>>>>>>> ServletContextAware"); } }
方式 4 实现ServletContextListener接口
import org.springframework.stereotype.Component; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; @Component public class DemoServletContextListener implements ServletContextListener { // 在初始化Web应用程序中的任何过滤器或servlet之前,将通知所有servletContextListener上下文初始化 @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("------------>>>>>>>>>> ServletContextListener"); } }
方法5 :将要执行的方法所在的类交个spring容器扫描(@Component),并且在要执行的方法上
添加@PostConstruct注解或者静态代码块执行
import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @Component public class DemoClass { // 静态代码块会在依赖注入后自动执行,并优先执行 static { System.out.println("------------>>>>>>>>>> static"); } // 在依赖注入完成后自动调用 @PostConstruct public static void demo() { System.out.println("------------>>>>>>>>>> PostConstruct"); } }