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