I have the following spring controller code:
@Controller
@RequestMapping("/")
public class MainController {
UserService user = new UserService();
@GetMapping("/home")
public String goFirstPage(){
user.showUserName(new User("Mike"));
return"firstpage";
}
}
and the following aspect:
@Aspect
@Component
@Order(1)
public class UserAspect {
@Before("execution(public void com.project.aopmaven.services.UserService.showUserName(..))")
public void logUser(){
System.out.println("Logging User");
}
}
It doesn't work, "Logging User" message is not shown (even the UserService object is instantiated in the controller class). But, when we add the @Autowired
annotation to the UserService defined in the controller it works!
@Autowired
UserService user = new UserService();
Can anyone explain this?
Spring AOP allows using AOP on Spring beans, not on random objects. And it's based on proxies: instead of injecting the actual implementation of the bean, Spring injects a proxy that wraps the actual implementation, and invokes the aspects before/after invoking the wrapped bean implementation.