在一个非常大的遗留应用程序中,我有没有实现这些接口的接口和类.
接口是基于类生成的,因此签名是相同的(除了接口在顶部添加另一个异常)并且名称相似(因此很容易从接口名称中找到类名).
为了获得接口的实现,我们做了一堆处理和记录调用,但基本上使用java.lang.reflect.Proxy委托给类.简化它看起来像这样:
// This will create a proxy and invoke handler that calls HelloWorld.doSomething
HelloWorldInterface i = MyProxyUtil.getInstance(HelloWorldInterface.class);
i.doSomething();
public interface HelloWorldInterface {
public void doSomething() throws Exception;
}
public class HelloWorld {
public void doSomething() {
//something
}
}
是否有可能使用Spring注释处理,一般@Autowire所有类型*接口的字段并且有春天使用MyProxyUtil.getInstance(* Interface.class)注入实现?
这样
@Autowire HelloWorldInterface a;
HelloWorldInterface b = MyProxyUtil.getInstance(HelloWorldInterface.class);
@Autowire AnotherInterface c;
AnotherInterface d = MyProxyUtil.getInstance(AnotherInterface.class);
a == b
c == d
最佳答案
是的,您需要实现AutowireCandidateResolver.
原文链接:https://www.f2er.com/spring/432767.html例如:
public class ProxyAutowiredCandidateResolver extends SimpleAutowireCandidateResolver {
@Override
public Object getSuggestedValue(DependencyDescriptor descriptor) {
String dependencyClassName = descriptor.getDependencyType().getSimpleName();
if (dependencyClassName.endsWith("Interface")) {
return MyProxyUtil.getInstance(descriptor.getDependencyType());
}
return super.getSuggestedValue(descriptor);
}
}
您可以使用beanfactoryPostProcessor在应用程序上下文中配置它:
public class AutowireCandidateResolverConfigurer implements beanfactoryPostProcessor {
private AutowireCandidateResolver autowireCandidateResolver;
public void postProcessbeanfactory(
ConfigurableListablebeanfactory beanfactory) throws BeansException {
DefaultListablebeanfactory bf = (DefaultListablebeanfactory) beanfactory;
bf.setAutowireCandidateResolver(autowireCandidateResolver);
}
public AutowireCandidateResolver getAutowireCandidateResolver() {
return autowireCandidateResolver;
}
public void setAutowireCandidateResolver(
AutowireCandidateResolver autowireCandidateResolver) {
this.autowireCandidateResolver = autowireCandidateResolver;
}
}