它在Java 的PostConstruct 文档页面中说
此注解只能注解一种方法
但我只是尝试用 PostConstruct 注释独立应用程序的三个方法。没有编译错误,三个都被顺利调用和执行。
那么我错过了什么?在什么样的类中可以和不能存在多个 PostConstruct 注释?
它在Java 的PostConstruct 文档页面中说
此注解只能注解一种方法
但我只是尝试用 PostConstruct 注释独立应用程序的三个方法。没有编译错误,三个都被顺利调用和执行。
那么我错过了什么?在什么样的类中可以和不能存在多个 PostConstruct 注释?
是的,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
这可能取决于您使用的 CDI 实现。您确实注入了具有注释的对象,不是吗?
我刚刚用 WELD 试了一下,它按预期抛出了一个异常:
WELD-000805: Cannot have more than one post construct method annotated with @PostConstruct for [EnhancedAnnotatedTypeImpl] public class Test
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");
}
然后执行将相应地排序,如下图所示:
在单个类中,它允许有多个带@PostConstruct
注释的方法,并且执行顺序是随机的。
@PostConstruct
public void myInit() {
System.out.println("inside the post construct method1. ");
}
@PostConstruct
public void myInit2() {
System.out.println("inside the post construct method2. ");
}
@PostConstruct
public void myInit3() {
System.out.println("inside the post construct method3. ");
}
@PostConstruct
public void myInit4() {
System.out.println("inside the post construct method4. ");
}
输出
FINE: Creating shared instance of singleton bean 'employee'
inside the default constructor....
inside the post construct method4.
inside the post construct method.
inside the post construct method2.
inside the post construct method3.
我用 2 个 @PostConstruct 测试了一个类,然后我收到错误 WELD-000805:不能有多个后构造方法但是如果我有多个 @PostConstruct,每个都在一个类中也没关系。所以我猜这句话的意思是:每个类只能用这个注解注解一个方法。