gpt4 book ai didi

java - Spring ProxyFactoryBean服务拦截不独特

转载 作者:太空宇宙 更新时间:2023-11-04 07:09:06 26 4
gpt4 key购买 nike

在使用ProxyFactoryBean和MethodInterceptor拦截多个服务接口(interface)时,当服务接口(interface)方法名相同时,拦截器由于某种原因将服务接口(interface)混淆了。我的问题是:

1.)使用单个ProxyFactoryBean拦截多个接口(interface)时是否需要遵守规则?

2.)代码哪里出了问题?我尝试在“proxyInterfaces”列表中切换 AnotherService 和 AService 的顺序,但这也不起作用。

3.) 我通过将 ProxyFactoryBean 一分为二解决了这个问题(请参阅底部的“解决方法”)。这是唯一的解决方案,还是有办法让我按照“代码”部分中的描述保留 ProxyFactoryBean?

代码:

我有几个使用 ProxyFactoryBean 拦截的服务:

<bean name="MyInterceptor" class="com.test.MyInterceptor">

<bean class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>MyInterceptor</value>
</list>
</property>
<property name="proxyInterfaces">
<list>
<value>com.test.AService</value>
<value>com.test.AnotherService</value>
</list>
</property>
</bean>

拦截器类 MyInterceptor 实现“调用”,如下所示:

public Object invoke(MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
String interfaceName = method.getDeclaringClass().getName();
System.out.println(interfaceName + ": " + method.getName());
}

Service接口(interface)声明如下:

public interface AService{
public void delete();

public void test();
}

public interface AnotherService{
public void delete();
}

现在,当我将 AService Autowiring 到一个类中时,我希望可以使用 AService 的删除和测试功能:

public class Test{

@Autowired
private AService aService;

public void testAservice(){
aService.test();
aService.delete();
}

}

在我的拦截器中,“aService.test()”调用毫无问题地到达。然而,“aService.delete()”调用以某种方式触发了 AnotherService 接口(interface)。拦截器的控制台输出如下:

com.test.AService: test
com.test.AnotherService: delete

解决方法:我将 ProxyFactoryBean 一分为二,使用两个单独的拦截器 bean(两者都引用与之前相同的类):

<bean name="MyInterceptor1" class="com.test.MyInterceptor"/>
<bean class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>MyInterceptor1</value>
</list>
</property>
<property name="proxyInterfaces">
<list>
<value>com.test.AService</value>
</list>
</property>
</bean>

<bean name="MyInterceptor2" class="com.test.MyInterceptor"/>
<bean class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>MyInterceptor2</value>
</list>
</property>
<property name="proxyInterfaces">
<list>
<value>com.test.AnotherService</value>
</list>
</property>
</bean>

现在,此配置会产生预期的输出:

com.test.AService: test
com.test.AService: delete

最佳答案

代理只是列出的接口(interface)的实现,但在 Java 中,不可能从多个接口(interface)实现相同的方法而不发生冲突。

请参阅this例如线程。

因此,只需保留您的解决方法或将删除方法名称更改为不同的(恕我直言,这是更好的选择)。

关于java - Spring ProxyFactoryBean服务拦截不独特,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20908919/

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