例如,您可以执行以下操作:
@Named
public class Foo{
public void blah(){
MyClass myClass = getBean(MyClass.class);
}
private <T> T getBean(Class<T> type) {
return context.getBean(Introspector.decapitalize(type.getSimpleName()), type);
}
}
@Inject
但这在使用or时不起作用@Autowire
。
要在自动装配时强制进行严格的类匹配,您可以用 a替换默认值AutowireCandidateResolver
,但这似乎不是一个好主意,因为或者可以解决 NUBDE 问题。BeanFactory
BeanFactoryPostprocessor
@Resource
@Qualify
例如:(未测试)
public class StrictClassAutowireCandidateResolver implements AutowireCandidateResolver {
@Override
public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
if (!bdHolder.getBeanDefinition().isAutowireCandidate()) {
return false;
}
if (descriptor == null) {
return true;
}
String className = null;
if (descriptor.getField() != null) {
className = descriptor.getField().getType().getName();
}
else if (descriptor.getMethodParameter() != null) {
className = descriptor.getMethodParameter().getParameterType().getName();
}
Class<?> clazz = null;
try {
clazz = Class.forName(className);
}
catch (Exception e) {
return false;
}
if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
// have no chances to be strict, let BeanFactory to find implementations.
return true;
}
return bdHolder.getBeanDefinition().getBeanClassName().equals(className);
}
@Override
public Object getSuggestedValue(DependencyDescriptor descriptor) {
return null;
}
}