Question

In Spring Framework, I am facing a strange issue while working with AOP. I have the following simple bean class for a greeting:

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");
    }
}

Below spring config:

<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 Advice Methods:

public class ServiceCheck {

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

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

Test Class:

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());

    }
}

Output:

Runs before the greeting
Runs after the greeting
Hello World

Question:

Why are both advices (before and after) getting printed when I use getter as a pointcut. The advice work correctly when i use pointcut on displayGreeting() method??

No correct solution

OTHER TIPS

The System.out.println() is executed after the hello.getMessage(). You can check it with the debuger.

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

Try to print something in hello.getMessage(), it will be printed between pre and post RunMessage methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top