fix: support @PostConstruct methods in parent classes

Recursively scan parent class hierarchy to collect all @PostConstruct
methods, ensuring parent methods are executed before child methods.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Timi
2026-01-13 16:21:40 +08:00
parent f5c6dcd275
commit c408107c48

View File

@ -254,14 +254,21 @@ public class BeanScanner {
private List<Method> findPostConstructs(Class<?> clazz) { private List<Method> findPostConstructs(Class<?> clazz) {
List<Method> methods = new ArrayList<>(); List<Method> methods = new ArrayList<>();
for (Method method : clazz.getDeclaredMethods()) { Class<?> currentClass = clazz;
// 从当前类向上遍历到 Object收集所有 @PostConstruct 方法
while (currentClass != null && currentClass != Object.class) {
for (Method method : currentClass.getDeclaredMethods()) {
if (method.isAnnotationPresent(PostConstruct.class)) { if (method.isAnnotationPresent(PostConstruct.class)) {
if (method.getParameterCount() != 0) { if (method.getParameterCount() != 0) {
throw new InjectException("@PostConstruct method must have no parameters: %s".formatted(method.getName())); throw new InjectException("@PostConstruct method must have no parameters: %s".formatted(method.getName()));
} }
methods.add(method); // 添加到列表头部,确保父类方法先执行
methods.addFirst(method);
} }
} }
currentClass = currentClass.getSuperclass();
}
return methods; return methods;
} }
} }