gpt4 book ai didi

java - 使用 ProxyFactory 实现编程式 Spring AOP

转载 作者:行者123 更新时间:2023-12-02 07:45:31 25 4
gpt4 key购买 nike

我正在尝试以编程方式实现 Spring AOP。我创建了一个简单的工厂类来生成 AOP Object.class 代理使用给定的 MethodInterceptor 列表:

public class AOPProxyFactoryBean implements FactoryBean<Object> {

private List<MethodInterceptor> methodInterceptors = new ArrayList<MethodInterceptor>();

public Object getObject() throws Exception {
Object o = new Object();
ProxyFactory proxyFactory = new ProxyFactory(o);
for (MethodInterceptor methodInterceptor : methodInterceptors) {
proxyFactory.addAdvice(methodInterceptor);
}
return proxyFactory.getProxy();
}

public Class<?> getObjectType() {
return Object.class;
}

public boolean isSingleton() {
return false;
}

public void setMethodInterceptors(List<MethodInterceptor> methodInterceptors) {
this.methodInterceptors = methodInterceptors;
}

一个简单的拦截器:

public class SimpleMethodInterceptor implements MethodInterceptor {

public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("SimpleMethodInterceptor: " + invocation.getMethod().getName());
return invocation.proceed();
}
}

Spring XML 配置:

<bean id="simpleMethodInterceptor" class="...SimpleMethodInterceptor"/>

<bean id="objectAOPProxyFactoryBean" class="...AOPProxyFactoryBean">
<property name="methodInterceptors">
<list>
<ref bean="simpleMethodInterceptor"/>
</list>
</property>
</bean>

在文档中here您可以阅读以下有关 addAdvice(Advice 建议) 的内容:'...请注意,给定的建议将应用于代理上的所有调用,甚至适用于 toString() 方法!...'

因此,我希望 SimpleMethodInterceptor 拦截对 Object.class 方法的所有调用。

测试:

@Test
public void aopTest() {
Object o = (Object) applicationContext.getBean("objectAOPProxyFactoryBean");
o.toString();
o.equals(o);
o.getClass();
}

给出这个输出:

SimpleMethodInterceptor:toString

似乎只有 toString() 方法被拦截。知道为什么吗?

最佳答案

奇怪。对我来说这似乎是一个错误。我无法准确解释原因,但我有一个可能的解决方法。创建一个接口(interface)并在那里重新定义 equals 和 hashCode:

public interface MadeUpInterface {
@Override
public boolean equals(Object obj);

@Override
public int hashCode();
}

返回一个从代理工厂实现该接口(interface)的实例。

public Object getObject() throws Exception {
Object o = new MadeUpInterface() {};
ProxyFactory proxyFactory = new ProxyFactory(o);
for (MethodInterceptor methodInterceptor : methodInterceptors) {
proxyFactory.addAdvice(methodInterceptor);
}
return proxyFactory.getProxy();
}

现在它将打印 equals 和 hashCode。所以我认为行为是它不会拦截仅在 Object 上定义的方法的调用。而 toString 被视为一种特殊情况。

关于java - 使用 ProxyFactory 实现编程式 Spring AOP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10928559/

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