springboot项目启动时执行的操作

注解@PostConstruct

使用@PostConstruct注解,该注解是Java5引入,表示项目在启动时候会执行被该注解修饰的方法。可以在下项目启动过程中做一些数据的常规化加载,可以加载一些数据库中的持久化数据到内存中。

@PostConstruct修饰的方法会在加载servlet的时候运行,且只会被执行一次。类似于Servlet的init()方法。被@PostConstruct修饰的方法会在构造方法之后,init()方法之前运行。

类似的注解还有@PreConstruct,被@PreConstruct修饰的方法在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法,被@PreConstruct修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。

整个执行顺序如下所示:

  1. 服务器加载Servlet
  2. servlet 构造函数的加载
  3. postConstruct
  4. init(init是在service 中的初始化方法. 创建service 时发生的事件.)
  5. Service
  6. destory
  7. predestory
  8. 服务器卸载serlvet

此外在执行@PostConstruct修饰的方法会在依赖注入完成后被自动调用,即会在 @Autowired依赖注入完成以后,再调用这个方法。

@Component
public class Test {
	@Autowired
	private UserService userService;
	
	@PostConstruct
	public void init(){
		List<User> userList = userService.selectAll();
		for (User user : userList) {
			System.out.println(user.toString());
		}
	}
	// 系统运行结束
	@PreDestroy
    public void destroy(){}
}

如上述代码所示,比较有意思的一点是如果在Test类中通过@Autowired获取一个实例,则spring会在运行init()方法之前完成userService的注入。

实现ServletContextAware接口并重写setServletContext方法

使用此方法时,会在填充完普通Bean的属性,但是还没有进行Bean的初始化之前

@Component
public class TestStarted implements ServletContextAware {
    /**
     * 在填充普通bean属性之后但在初始化之前调用
     * 类似于initializingbean的afterpropertiesset或自定义init方法的回调
     */
    @Override
    public void setServletContext(ServletContext servletContext) {
        System.out.println("setServletContext方法");
    }
}

实现ServletContextListener接口

在初始化web应用程序中的任何过滤器或servlet之前,将通知所有servletContexListener上下文初始化。重载contextInitialized方法。重载contextDestroyed方法,在项目运行结束之前进行一些操作。

@Component
public class TestListener implements ServletContextListener {
    /**
     * 在初始化Web应用程序中的任何过滤器或servlet之前,将通知所有servletContextListener上下文初始化。
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) 
        System.out.println("执行contextInitialized方法");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("执行contextDestroyed方法");
    }
}

实现ApplicationRunner接口

用于指示bean包含在SpringApplication中应运行的接口,可以定义多个application bean ,在同一应用程序上下文中,可以使用有序接口或@order注解进行排序

  @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner的run方法");
    }

实现CommandLineRunner接口

用于指示bean包含在SpringApplication中时应运行的接口。可以在同一应用程序上下文中定义多个commandlinerunner bean,并且可以使用有序接口或@order注释对其进行排序。如果需要访问applicationArguments而不是原始字符串数组,请考虑使用applicationrunner。

@Override
public void run(String... ) throws Exception {
	System.out.println("CommandLineRunner的run方法");
}

参考

https://www.cnblogs.com/lsgspace/p/10508180.html

posted @ 2021-06-11 15:47  卡洛小豆  阅读(1007)  评论(0编辑  收藏  举报