From f9c1a4aeb65803b438fa19009dd37b190fee4178 Mon Sep 17 00:00:00 2001 From: Timi Date: Thu, 15 Jan 2026 18:38:31 +0800 Subject: [PATCH] feat: add fallback bean resolution by parameter/field name - Replace javafx-maven-plugin with maven-compiler-plugin - Enable -parameters flag for runtime parameter name access - Add getBeanWithFallback for name-based disambiguation when multiple candidates exist Co-Authored-By: Claude Opus 4.5 --- pom.xml | 8 ++--- .../java/com/imyeyu/inject/BeanFactory.java | 33 +++++++++++++++++-- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/pom.xml b/pom.xml index ffd9851..e7bfc27 100644 --- a/pom.xml +++ b/pom.xml @@ -44,11 +44,11 @@ - org.openjfx - javafx-maven-plugin - 0.0.8 + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 - com.imyeyu.inject.javafxdemo.FxMain + true diff --git a/src/main/java/com/imyeyu/inject/BeanFactory.java b/src/main/java/com/imyeyu/inject/BeanFactory.java index 2217ffa..7065ad8 100644 --- a/src/main/java/com/imyeyu/inject/BeanFactory.java +++ b/src/main/java/com/imyeyu/inject/BeanFactory.java @@ -172,7 +172,8 @@ public class BeanFactory { return getBean(qualifier.value()); } Class type = parameter.getType(); - return getBean(type); + String paramName = parameter.getName(); + return getBeanWithFallback(type, paramName); } private void invokePostConstruct(Object instance, BeanDefinition definition) { @@ -258,6 +259,34 @@ public class BeanFactory { return getBean(qualifier.value()); } Class type = field.getType(); - return getBean(type); + String fieldName = field.getName(); + return getBeanWithFallback(type, fieldName); + } + + /** + * 按类型获取 bean,当存在多个候选时按名称回退匹配 + * + * @param type 类型 + * @param name 字段名或参数名,用于歧义时的回退匹配 + * @return bean 实例 + */ + private Object getBeanWithFallback(Class type, String name) { + List candidates = context.getBeanNamesByType(type); + if (candidates.isEmpty()) { + throw new InjectException("Bean not found for type: %s".formatted(type.getName())); + } + if (candidates.size() == 1) { + return getBean(candidates.getFirst()); + } + // 多个候选时,先尝试按名称精确匹配 + if (candidates.contains(name)) { + return getBean(name); + } + // 再尝试 @Primary + String primaryBean = findPrimaryBean(candidates); + if (primaryBean != null) { + return getBean(primaryBean); + } + throw new InjectException("Multiple beans found for type %s: %s - use @Qualifier or @Primary to specify which one to inject".formatted(type.getName(), candidates)); } }