0

I am working on spring application, I want to trigger the aspect @Before whenever any of the setxx(..) methods are being called in the class.When the Details class is executed, the SetterInterceptor @Before aspect is not being called.

I have the below classes:

package com.mypack;
public class Person {
    private String id;
    private String firstName;
    private String lastName;

    public String getId() { return id; }
    public String getFirstName() { return firstName; }
    public String getLastName() { return lastName; }

    public void setId(String id) { this.id = id; }
    public void setFirstName(String firstName) { this.firstName = firstName; }
    public void setLastName(String lastName) { this.lastName = lastName; }
    public String toString() { return "Person[" + id + ",  
   + firstName + ", " + lastName+ "]"; }
}

Details class:

package com.mypack;
public class Details extends Person{

    private String address;
    private String contactNum;
    //getters and setters
    public String toString() { return "Details[" + address + ", 
    " + contactNum+ "]"; }

    public static void main(String[] args) {
    Details obj1 = new Details();
    obj1.setAddress("xx 202");
    obj1.setContactNum("2124551234");
    obj1.setId("242");
    obj1.setFirstName("John");
    obj1.setLastName("John");

    Details obj2 = new Details();
    obj2.setAddress("ASDf 202");
    obj2.setContactNum("234544565656");
    obj2.setId("23689");
    obj2.setFirstName("Sam");
    obj2.setLastName("S");

    System.out.println("obj1 : " + obj1);
    System.out.println("obj2 : " + obj2);

    obj2.setFirstName("Samuel");
}

}

SetterInterceptor class:

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class SetterInterceptor {
     @Before("execution(* com.mypack.Details.set*(*))")
        public void before(JoinPoint joinPoint) throws Throwable {
        Object[] signatureArgs = joinPoint.getArgs();
            for (Object signatureArg : signatureArgs) {
                Person obj = (Person) signatureArg;
                System.out.println("Before : " + obj.getFirstName() + " ---- "
                        + obj.getId());

            }

        }
}

Any inputs are helpful.

user222
  • 587
  • 3
  • 10
  • 31

1 Answers1

1

From documentation on Spring AOP (emphasis mine):

Spring AOP currently supports only method execution join points (advising the execution of methods on Spring beans)

In other words any method calls that you want intercepted need to be on beans instantiated by Spring.

In your example the application is not even a Spring application (you don't have an ApplicationContext) and you create the instance of Details by using new.

Strelok
  • 50,229
  • 9
  • 102
  • 115