0

我尝试编写一个简单的 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>

但结果仍然只有“世界”,而预期的结果是“你好世界!”

4

1 回答 1

0

在 xml 配置中,为什么您的某些包路径有两个点?例如:

<aop:pointcut id="helloExecution"
        expression="execution(* com..playground..writeMessage*()) and args(invocation)" />

应该:

<aop:pointcut id="helloExecution"
        expression="execution(* com.playground.writeMessage*()) and args(invocation)" />

和其他一些地方:

<bean id="advice" class="com.playground.aophelloworld.MessageDecorator" />
<bean id="myBeanOfHelloWorld" class="com.playground.aophelloworld.MyBeanOfHelloWorld">
    <property name="messageWriterStdOut" ref="messageWriterStdOut" />

更新:你可以试试这个:

<aop:pointcut id="helloExecution"
        expression="execution(* com..playground.MessageWriterStdOut.writeMessage(..))" />
于 2012-11-16T16:49:40.047 回答