软件编程
位置:首页>> 软件编程>> java编程>> Spring框架中@PostConstruct注解详解

Spring框架中@PostConstruct注解详解

作者:大局观的小老虎  发布时间:2021-09-20 09:35:58 

标签:@postconstruct,注解,spring

初始化方式一:@PostConstruct注解

假设类UserController有个成员变量UserService被@Autowired修饰,那么UserService的注入是在UserController的构造方法之后执行的。

如果想在UserController对象生成时候完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入的对象,那么就无法在构造函数中实现(ps:spring启动时初始化异常),例如:

public class UserController {
   @Autowired
   private UserService userService;

public UserController() {
       // 调用userService的自定义初始化方法,此时userService为null,报错
       userService.userServiceInit();
   }
}

因此,可以使用@PostConstruct注解来完成初始化,@PostConstruct注解的方法将会在UserService注入完成后被自动调用。

public class UserController {
   @Autowired
   private UserService userService;

public UserController() {
   }

// 初始化方法
   @PostConstruct
   public void init(){
       userService.userServiceInit();
   }
}

总结:类初始化调用顺序:

(1)构造方法Constructor

(2)@Autowired

(3)@PostConstruct

初始化方式二:实现InitializingBean接口

除了采用注解完成初始化,也可以通过实现InitializingBean完成类的初始化

public class UserController implements InitializingBean {
   @Autowired
   private UserService userService;

public UserController() {
   }

// 初始化方法
   @Override
   public void afterPropertiesSet() throws Exception {
       userService.userServiceInit();
   }
}

比较常见的如SqlSessionFactoryBean,它就是通过实现InitializingBean完成初始化的。

@Override
public void afterPropertiesSet() throws Exception {
// buildSqlSessionFactory()是完成初始化的核心方法,必须在构造方法调用后执行
this.sqlSessionFactory = buildSqlSessionFactory();
}

补充:@PostConstruct注释规则

  1. 除了 * 这个特殊情况以外,其他情况都不允许有参数,否则spring框架会报IllegalStateException;而且返回值要是void,但实际也可以有返回值,至少不会报错,只会忽略

  2. 方法随便你用什么权限来修饰,public、protected、private都可以,反正功能是由反射来实现

  3. 方法不可以是static的,但可以是final的

所以,综上所述,在spring项目中,在一个bean的初始化过程中,方法执行先后顺序为

Constructor > @Autowired > @PostConstruct

先执行完构造方法,再注入依赖,最后执行初始化操作,所以这个注解就避免了一些需要在构造方法里使用依赖组件的尴尬。

来源:https://blog.csdn.net/m0_53288098/article/details/122355201

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com