Prabhjot
Prabhjot

Reputation: 5014

Spring AOP expression executed but it shouldn't

I am newbie in Spring and trying to understand AOP. Here's what I got

I have one simple aspect, which I want to run when any non-getter method gets called

@Aspect
@Component
public class LoggingAspect {

    @Pointcut("execution(* org.practice.entity.Person.get*())")
    private void getter() {}

    @Before("!getter()")
    public void noGetter() {
        System.out.println("NO GETTER GETS CALLED");
    }
}

Person class is simply

@Component
public class Person {
    public void getPerson() {
        System.out.println("GETTING PERSON....");
    }
 }

I am initializing the config using Java annotations

@Configuration
@EnableAspectJAutoProxy
@ComponentScan("org.practice")
public class DemoConfig {}

And then in my main method i have

public class MyApp {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class);
        context.close();
    }
}

As you can see I am simply creating a context and closing it and not calling any getter or non-getter method. When I run the program, I got the following console output

NO GETTER GETS CALLED....

This makes semi-sense as I am not calling any getter method, but I expected this aspect to execute only if I am explicitly calling any non-getter not by just opening the context. Please let me know if I want my business logic to execute only if any non-getter method gets invoked then how would I do it?

Thanks

Upvotes: 0

Views: 51

Answers (2)

codeLover
codeLover

Reputation: 2592

I think its happening during the initializing of Person bean at the time od application context loading Since you have given joinpoint as not of getter so at the time of default construction execution (provided by compiler) the advice is getting triggered

Upvotes: 1

Elvermg
Elvermg

Reputation: 447

Try this:

@Pointcut("execution(* org.practice.entity.Person.*())")
     private void methodCall() {}

@Before("!getter() && methodCall")
    public void noGetter() {
        System.out.println("NO GETTER GETS CALLED");
    }

Upvotes: 1

Related Questions