我尝试编写一个简单的 AOP 程序,并像下面这样配置 xml 文件。但是当我运行程序时,结果似乎没有调用建议,而只执行了非建议部分。
这是方法类:
public class MessageWriterStdOut {
public void writeMessage() {
System.out.print("World");
}
}
这是豆类:
public class MyBeanOfHelloWorld {
private MessageWriterStdOut messageWriterStdOut;
public void execute() {
messageWriterStdOut.writeMessage();
}
public void setMessageWriterStdOut(MessageWriterStdOut messageWriterStdOut) {
this.messageWriterStdOut = messageWriterStdOut;
}
}
建议类是这样的:
public class MessageDecorator implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.print("Hello ");
Object retVal = invocation.proceed();
System.out.println("!");
return retVal;
}
}
主要方法是:
public class HelloWorldAopExample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("/META-INF/spring/context-aop.xml");
ctx.refresh();
MyBeanOfHelloWorld myBeanOfHelloWorld = (MyBeanOfHelloWorld) ctx.getBean("myBeanOfHelloWorld");
myBeanOfHelloWorld.execute();
}
}
xml配置是:
<aop:config>
<aop:pointcut id="helloExecution"
expression="execution(* com..playground..writeMessage*()) and args(invocation)" />
<aop:aspect ref="advice">
<aop:around pointcut-ref="helloExecution" method="invoke" />
</aop:aspect>
</aop:config>
<bean id="advice" class="com..playground.aophelloworld.MessageDecorator" />
<bean id="messageWriterStdOut"
class="com..playground.aophelloworld.MessageWriterStdOut" />
<bean id="myBeanOfHelloWorld" class="com..playground.aophelloworld.MyBeanOfHelloWorld">
<property name="messageWriterStdOut" ref="messageWriterStdOut" />
</bean>
但结果仍然只有“世界”,而预期的结果是“你好世界!”