bean初始化完成后如何调用方法?
我有一个用例,我需要在 ApplicationContext 加载时仅调用一次 bean 中的(非静态)方法。 如果我使用 MethodInvokingFactoryBean 可以吗? 或者我们有更好的解决方案?
附带说明一下,我使用 ConfigContextLoaderListener 在 Web 应用程序中加载应用程序上下文。 并且希望,如果 bean 'A' 被实例化,只需调用 methodA() 一次。
这件事怎样才能做得好呢?
I have a use case where I need to call a (non-static) method in the bean only-once at the ApplicationContext load up. Is it ok, if I use MethodInvokingFactoryBean for this? Or we have a some better solution?
As a side note, I use ConfigContextLoaderListener to load the Application Context in web application. And want, that if bean 'A' is instantiated just call methodA() once.
How can this be done nicely?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
为了扩展其他答案中的 @PostConstruct 建议,在我看来,这确实是最好的解决方案。
@PostConstruct
位于javax.*
中)。To expand on the
@PostConstruct
suggestion in other answers, this really is the best solution, in my opinion.@PostConstruct
is injavax.*
)您可以使用类似的方法:
这将在实例化 bean 时调用“init”方法。
You can use something like:
This will call the "init" method when the bean is instantiated.
需要考虑三种不同的方法,如 参考
使用 init-method 属性
优点:
缺点:
实现InitializingBean
优点:
缺点:
使用 JSR-250 @PostConstruct 生命周期注释
优点:
缺点:
There are three different approaches to consider, as described in the reference
Use init-method attribute
Pros:
Cons:
Implement InitializingBean
Pros:
Cons:
Use JSR-250 @PostConstruct lifecyle annotation
Pros:
Cons:
您是否尝试过实施
InitializingBean
? 听起来正是您所追求的。缺点是您的 bean 变得支持 Spring,但在大多数应用程序中这还不错。
Have you tried implementing
InitializingBean
? It sounds like exactly what you're after.The downside is that your bean becomes Spring-aware, but in most applications that's not so bad.
您可以部署自定义 BeanPostProcessor< /a> 在您的应用程序上下文中执行此操作。 或者,如果您不介意在 bean 中实现 Spring 接口,则可以使用 InitializingBean 接口或“init-method”指令(相同链接)。
You could deploy a custom BeanPostProcessor in your application context to do it. Or if you don't mind implementing a Spring interface in your bean, you could use the InitializingBean interface or the "init-method" directive (same link).
为了进一步消除对这两种方法的任何混淆,即使用
@PostConstruct
和init-method="init"
从个人经验来看,我意识到使用 (1) 仅适用于servlet 容器,而 (2) 可在任何环境中工作,甚至在桌面应用程序中。 因此,如果您要在独立应用程序中使用 Spring,则必须使用 (2) 来执行“初始化后调用此方法”。
To further clear any confusion about the two approach i.e use of
@PostConstruct
andinit-method="init"
From personal experience, I realized that using (1) only works in a servlet container, while (2) works in any environment, even in desktop applications. So, if you would be using Spring in a standalone application, you would have to use (2) to carry out that "call this method after initialization.