gpt4 book ai didi

java - Spring:委托(delegate)给自定义代理包装器进行接口(interface)注入(inject)

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:59:12 29 4
gpt4 key购买 nike

在一个非常大的遗留应用程序中,我有一些接口(interface)和类实现这些接口(interface)。

接口(interface)是基于类生成的,所以签名相同(除了接口(interface)在上面添加了另一个异常(exception))并且名称相似(因此很容易从接口(interface)名称中找到类名)。

为了实现接口(interface),我们进行了一系列处理和记录调用,但基本上使用 java.lang.reflect.Proxy 委托(delegate)给类。简化后看起来像这样:

// 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 所有 *Interface 类型的字段,并让 spring 使用 MyProxyUtil.getInstance(*Interface.class ) 注入(inject)实现?

这样

@Autowire HelloWorldInterface a;

HelloWorldInterface b = MyProxyUtil.getInstance(HelloWorldInterface.class);

@Autowire AnotherInterface c;

AnotherInterface d = MyProxyUtil.getInstance(AnotherInterface.class);


a == b
c == d

最佳答案

是的,您需要实现一个AutowireCandidateResolver

例如:

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;
}

}

<bean id="autowireCandidateResolverConfigurer" class="AutowireCandidateResolverConfigurer">
<property name="autowireCandidateResolver">
<bean class="ProxyAutowiredCandidateResolver" />
</property>
</bean>

关于java - Spring:委托(delegate)给自定义代理包装器进行接口(interface)注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17687240/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com