If i keep @Pointcut("within(org.example.ShoppingCart.*)")
in AuthenticationAspect.java
then the authenticate
method is NOT getting invoked BUT when i change to @Pointcut("within(org.example..*)")
then it does get invoked.
Doesn't the 2nd PointCut below automatically include the first one?
@Pointcut("within(org.example.ShoppingCart.*)")
@Pointcut("within(org.example..*)")
i believe both of these should work.
Following is the code :
ShoppingCart.java
package org.example;
import org.springframework.stereotype.Component;
@Component
public class ShoppingCart {
public void checkout(String status)
{
System.out.println("Checkout method called");
}
}
AuthenticationAspect.java
package org.example;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AuthenticationAspect {
@Pointcut("within(org.example.ShoppingCart.*)")
public void authenticationPointCut()
{
}
@Before("authenticationPointCut()")
public void authenticate()
{
System.out.println("Authentication is being performed");
}
}
Main.java
package org.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
ShoppingCart cart = context.getBean(ShoppingCart.class);
cart.checkout("CANCELLED");
}
}
BeanConfig.java
package org.example;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration // Indicates this is a configuration class
@ComponentScan(basePackages = "org.example") // Indicates where to find the components/beans
@EnableAspectJAutoProxy // Enables the AspectJ features in project
public class BeanConfig {
}
i am learning spring aspect and unsure why the pointcut expression is not working .
Since the within
pointcut designator limits matching to join points of certain types, the problem is your pointcut expression is matching types within ShoppingCart
because of .*
in the end. If you remove those characters it should work.
@Pointcut("within(org.example.ShoppingCart)")
public void authenticationPointCut(){}