Spring @PostConstruct与init-method属性 [英] Spring @PostConstruct vs. init-method attribute

查看:77
本文介绍了Spring @PostConstruct与init-method属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Spring XML配置中使用@PostConstruct注释和声明与init-method相同的方法之间是否有区别?

Is there any difference between using the @PostConstruct annotation and declaring the same method as init-method in Spring XML configuration?

推荐答案

实际上,我认为这没有什么区别,但是它们的工作方式有优先考虑的地方. @PostConstructinit-method是BeanPostProcessor.

No practically I don't think there is any difference but there are priorities in the way they work. @PostConstruct, init-method are BeanPostProcessors.

  1. @PostConstruct是JSR-250批注,而init-method是Spring的初始化方法.
  2. 如果有@PostConstruct方法,则将在调用初始化方法之前先调用此方法.
  3. 如果您的bean实现了InitializingBean并覆盖了afterPropertiesSet,则首先调用@PostConstruct,然后调用afterPropertiesSet,然后调用init-method.
  1. @PostConstruct is a JSR-250 annotation while init-method is Spring's way of having an initializing method.
  2. If you have a @PostConstruct method, this will be called first before the initializing methods are called.
  3. If your bean implements InitializingBean and overrides afterPropertiesSet , first @PostConstruct is called, then the afterPropertiesSet and then init-method.

有关更多信息,您可以查看Spring的

For more info you can check Spring's reference documentation.

在JSR 250规范之前,在xml中使用init-method是首选方式,因为它将Java类(beans)与任何特定于Spring的类/注释分离开. Spring基础结构Bean,则首选使用init-method.在创建方法期间,您可以指定需要称为初始化方法的方法.

Before JSR 250 specs , usage of init-method in xml was preferred way , as it decouples java classes (beans) from any spring specific classes/annotations.So if you are building a library that does not need to be dependent on spring infrastructure beans then use of init-method was preferred.During creation method u can specify the method that needs to be called as initialization method.

现在,随着Java EE中JSR 250规范的引入以及这些注释的Spring支持,对Spring框架的依赖性已在一定程度上降低了.

Now with introduction of JSR 250 specs in Java EE and spring support of these annotations , dependency on spring framework has been reduced to a certain extent.

但是我不得不承认,添加这些内容可以提高代码的可读性.因此,这两种方法都各有利弊.

But i have to admit that addition of these things increase the readability of code.So there are pros and cons both approaches.

这篇关于Spring @PostConstruct与init-method属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆