建站宝盒全能版,自助云商城,点了网站域名会跳转,网站 seo 如何使用 PostConstruct、 Autowired与构造函数的执行顺序 一、PostConstruct介绍二、Spring框架中在bean初始化和销毁时候执行实现方式三、项目验证1.MyServiceImpl2.测试结果3. 项目源码 最近对同事代码进行codeReview时候发现用PostConstruct注解#xff0c;特地对此注解执行顺序进行… PostConstruct、 Autowired与构造函数的执行顺序 一、PostConstruct介绍二、Spring框架中在bean初始化和销毁时候执行实现方式三、项目验证1.MyServiceImpl2.测试结果3. 项目源码  最近对同事代码进行codeReview时候发现用PostConstruct注解特地对此注解执行顺序进行了研究整理记录如下。 一、PostConstruct介绍 
Java提供的注解被用来修饰方法被PostConstruct修饰的方法会在服务器加载Servlet的时候运行并且只会被服务器执行一次。PostConstruct在构造函数之后执行init方法之前执行。 
(1)结论 调用的顺序为 构造函数  Autowired  PostConstruct (2)作用 PostConstruct注解的方法在项目启动的时候执行这个方法也可以理解为在spring容器启动的时候执行可作为一些数据的常规化加载比如读取数据字典之类、目录树缓存 二、Spring框架中在bean初始化和销毁时候执行实现方式 
Spring框架中在bean初始化和销毁时候执行某个方法的三种实现方式。 (1)Spring框架中通过注解PostConastruct 和 PreDestroy来实现Bean初始化执行和销毁时候执行方法 
(2)Spring框架中通过实现接口InitializingBean ,DisposableBean来实现Bean初始化执行和销毁时候执行方法 
(3)Spring框架中通过xml配置文件中bean的init-method“” destroy-method来实现Bean初始化执行和销毁时候执行方法 
Spring Bean执行顺序  
三、项目验证 
1.MyServiceImpl 
package com.huahua.myIdea.service.serviceImpl;import com.huahua.myIdea.service.MyService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;Service
public class MyServiceImpl implements MyService, InitializingBean {Overridepublic int addTotal(int x, int y) {return 0;}Overridepublic void afterPropertiesSet() throws Exception {System.out.println(开始执行 afterPropertiesSet 方法: MyServiceImpl);}PostConstructpublic void postConstructMethod() {System.out.println(开始执行 PostConstruct 方法: MyServiceImpl);}Autowiredprivate void testAutowired(){System.out.println(开始执行 testAutowired 方法: MyServiceImpl);}MyServiceImpl(){System.out.println(开始执行 构造函数MyServiceImpl : MyServiceImpl);}
}2.测试结果 3. 项目源码 
项目结构及代码下载欢迎star~~ MyIdea  参考资料 InitializingBean、BeanPostProcessor、init-method、PostConstruct执行先后顺序 SpringBoot 学习之 PostConstruct、 Autowired与构造函数的执行顺序