它在Java文档页面中为PostConstruct写到
只有一个方法可以使用此注释进行注释。
但我只是尝试用PostConstruct注释独立应用程序的三种方法。没有编译错误,它们都被调用并顺利执行。
那我错过了什么?哪些类可以存在多个PostConstruct注释,哪些类不能存在?
发布于 2016-07-06 01:42:17
是的,看来Spring没有遵循这个限制。我找到了处理这个注释(即InitDestroyAnnotationBeanPostProcessor )的代码,以及具体的方法:
public void invokeInitMethods(Object target, String beanName) throws Throwable {
Collection<LifecycleElement> initMethodsToIterate =
(this.checkedInitMethods != null ? this.checkedInitMethods : this.initMethods);
if (!initMethodsToIterate.isEmpty()) {
boolean debug = logger.isDebugEnabled();
for (LifecycleElement element : initMethodsToIterate) {
if (debug) {
logger.debug("Invoking init method on bean '" + beanName + "': " + element.getMethod());
}
element.invoke(target);
}
}
}因此,spring支持多个PostConstruct
发布于 2014-03-14 09:27:17
这可能取决于您正在使用的CDI实现。您确实注入了对象,在其中有注释,不是吗?
我只是尝试了焊接,它抛出了一个异常,如预期:
WELD-000805: Cannot have more than one post construct method annotated with @PostConstruct for [EnhancedAnnotatedTypeImpl] public class Test发布于 2020-08-18 11:25:17
Spring支持多PostConstruct,在运行时,应用程序将选择先运行,在类中排序在首位。见下面的例子:
@PostConstruct
private void firstPostConstructor() {
LOGGER.info("First Post Constructor");
}
@PostConstruct
private void secondPostConstructor() {
LOGGER.info("Second Post Constructor");
}
@PostConstruct
public void thirdPostConstructor() {
LOGGER.info("Third Post Constructor");
}然后将相应地命令执行,如下图所示:

https://stackoverflow.com/questions/22400705
复制相似问题