Sring 通过手工编码方式基于类的代理实现前置增强

Waiter类:
public class Waiter {
public void greetTo(String name) {
System.out.println("waiter greet to "+name+"...");
}

public void serveTo(String name){
    System.out.println("waiter serving "+name+"...");
}

}
TestAdvisorByProxyFactory类:
public class TestAdvisorByProxyFactory {
public static void main(String[] args) {
Waiter waiterTarget = new Waiter();
BeforeAdvice advice = new GreetingBeforeAdvice();
Advisor advisor = new GreetingAdvisor();
ProxyFactory pf = new ProxyFactory();
pf.setOptimize(true);
pf.addAdvice(advice);
pf.addAdvisor(advisor);
Waiter waiter = (Waiter) pf.getProxy();
waiter.greetTo("john");
waiter.serveTo("john");
}
}
运行时候报错:
Exception in thread "main" org.springframework.aop.framework.AopConfigException: TargetSource cannot determine target class: Either an interface or a target is required for proxy creation.
at org.springframework.aop.framework.DefaultAopProxyFactory.createAopProxy(DefaultAopProxyFactory.java:56)
at org.springframework.aop.framework.ProxyCreatorSupport.createAopProxy(ProxyCreatorSupport.java:105)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:96)
at cn.zw.test.advisor.TestAdvisorByProxyFactory.main(TestAdvisorByProxyFactory.java:20)
怎么修改才能运行呢?

2个回答

自己来回答吧:
TestAdvisorByProxyFactory类:
public class TestAdvisorByProxyFactory {
public static void main(String[] args) {
Waiter waiterTarget = new Waiter();
BeforeAdvice advice = new GreetingBeforeAdvice();
//把织入切面注释掉
//Advisor advisor = new GreetingAdvisor();
ProxyFactory pf = new ProxyFactory();
pf.setOptimize(true);
pf.addAdvice(advice);
//pf.addAdvisor(advisor);
pf.setTarget(waiterTarget);
Waiter waiter = (Waiter) pf.getProxy();
waiter.greetTo("john");
waiter.serveTo("john");
}
}
现在还没找到织入切面了以后怎么运行,等找到了在更新。

补充:
在主函数中添加pf.setTarget(waiterTarget);

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐