karthik karthik - 8 days ago 7
Java Question

Spring AOP - Unable to execute Aspect

I am new to Spring AOP and annotations. I tried to write a simple program that uses Aspect. I am unable to figure out where I went wrong. Its doesn't print the what I have in my Aspect.

package com.business.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@EnableAspectJAutoProxy
@Configuration
public class PrintMain {

public static void main(String[] args) {
// Do I always need to have this. Can't I just use @Autowired to get beans
ApplicationContext ctx = new AnnotationConfigApplicationContext(TNGPrintMain.class);
CheckService ck = (CheckService)ctx.getBean("service");
ck.print();
}

@Bean(name="service")
public CheckService service(){
return new CheckService();
}

}

package com.business.main;

import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class SimpleAspect {

@Around("execution(* com.business.main.CheckService.*(..))")
public void applyAdvice(){
System.out.println("Aspect executed");
}
}

package com.business.main;

import org.springframework.stereotype.Component;

@Component
public class CheckService{
public void print(){
System.out.println("Executed service method");
}
}


Output: Executed service method

I expect to print what I have in my Aspect

Answer

I think your @Component isn't work!
Maybe, you need the @ComponentScan

@EnableAspectJAutoProxy
@ComponentScan
@Configuration
public class PrintMain {

    public static void main(String[] args) {
        // Do I always need to have this. Can't I just use @Autowired to get beans
        ApplicationContext ctx = new AnnotationConfigApplicationContext(TNGPrintMain.class);
        CheckService ck = (CheckService)ctx.getBean("service");
        ck.print();
    }

    @Bean(name="service")
    public CheckService service(){
        return new CheckService();
    }

}