0

簡単な AOP プログラムを作成しようとしましたが、xml ファイルを次のように構成しました。しかし、プログラムを実行すると、結果はアドバイスを呼び出すのではなく、アドバイス以外の部分を実行するだけのようです。

メソッドクラスは次のとおりです。

public class MessageWriterStdOut {
    public void writeMessage() {
        System.out.print("World");
    }
} 

これは Bean クラスです。

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>

しかし、結果はまだ "world" だけで、予想される結果は "hello world!" です。

4

1 に答える 1

0

xml構成で、パッケージパスの一部に2つのドットが含まれているのはなぜですか?例えば:

<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 に答える