Search code examples
javaspringaopspring-aop

AOP AfterReturning function returns twice


I have a little problem. I'm calling AfterReturning function after some function returns and my AfterReturning function's working twice and I don't want that. Here is the code:

@Aspect
@Component
@Configuration
public class AspectOP {

    LogController logcontroller = new LogController();

    @AfterReturning("execution(* com..*save*(..))")
    public void doSomething() {
        logcontroller.guestbook("XD");
    }
}

I have 2 save function and we changed names but it's same again. I've tried remove @Component or @Aspect then it's not working.

EDIT

My save function

@Controller
@RequestMapping("/api")
public class EntryController {

    @Autowired
    EntryRepository repo;
    Account account;

    @RequestMapping(path = "/getir", method = RequestMethod.GET)
    public @ResponseBody List<Entries> getir(){
        return repo.findAll();

    }

    @RequestMapping(path = "/saveentry", method = RequestMethod.POST, consumes = "application/json")
    public @ResponseBody Entries save(@RequestBody Entries entry) {
        return repo.save(entry);
    }
}

LogController.class

@Controller
public class LogController {

    @MessageMapping("/guestbook")
    @SendTo("/topic/entries")
    public Log guestbook(String message) {
        System.out.println("Received message: " + message);
        return new Log(message);
    }
}

My main objective is when something is saved, I send something to my socket. It's working but doSomething functions is working twice.


Solution

  • seems advice applied to your EntryRepository class as well. change your pointcut expression to something like, to be only applied to EntryController's save method

    @AfterReturning("execution(* com.xyz.EntryController.save*(..))")
    

    Examples here