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 <noreply@anthropic.com>
This commit is contained in:
8
pom.xml
8
pom.xml
@ -44,11 +44,11 @@
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-maven-plugin</artifactId>
|
||||
<version>0.0.8</version>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<mainClass>com.imyeyu.inject.javafxdemo.FxMain</mainClass>
|
||||
<parameters>true</parameters>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
@ -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<String> 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));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user