1

在 Spring Framework 中,我在使用 AOP 时遇到了一个奇怪的问题。我有以下简单的 bean 类作为问候语:

public class HelloBean {
    private String message;
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void displayGreeting() {
        System.out.println("Hello");
    }
}

下面的弹簧配置:

<beans>
    <bean id="hello" class="com.att.spring.main.HelloBean"/>

    <bean id="serviceCheck" class="com.att.spring.main.ServiceCheck" />

    <aop:config>
        <aop:aspect ref="serviceCheck"> 
            <aop:pointcut id="greet"
                expression="execution(* *.getMessage(..))" />
            <aop:before pointcut-ref="greet"
                method="preRunMessage" />
            <aop:after pointcut-ref="greet"
                method="postRunMessage" />
        </aop:aspect>
    </aop:config>
</beans>

AOP 建议方法:

public class ServiceCheck {

    public void preRunMessage() {
        System.out.println("Runs before the greeting");
    }

    public void postRunMessage() {
        System.out.println("Runs after the greeting");
    }
}

测试类:

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "spring-beans.xml");
        HelloBean hello = (HelloBean) context.getBean("hello");
        hello.setMessage("Hello World");
        System.out.println(hello.getMessage());

    }
}

输出:

Runs before the greeting
Runs after the greeting
Hello World

问题:

当我使用 getter 作为切入点时,为什么会打印两个建议(之前和之后)。当我在 displayGreeting() 方法上使用切入点时,建议可以正常工作??

4

1 回答 1

0

System.out.println()之后执行hello.getMessage()。您可以使用调试器检查它。

1)preRunMessage()
2)hello.getMessage()
3)postRunMessage()
4)the System.out.println() prints the string returned by hello.getMessage()

尝试在 中打印一些东西hello.getMessage(),它将在运行前和后运行消息方法之间打印。

于 2014-02-19T15:57:01.677 回答