简体   繁体   中英

Creating custom annotation in Java

I'm adding some logs to my Spring based application, I want to log for every method, the user that is doing the action. Below you can find an example of a method.

@Override
@Transactional
public void deleteAccount(Long id){
    String principal = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    MDC.put("username",principal);
    accountDao.remove(id);
    List<String> action = (List<String>) MDC.get("action");
    if (action == null)
        action=new ArrayList<String>();
    action.add("Deleted account with id:"+id);
    MDC.put("action", action);
}

The first two lines of the method are generic, so I want two avoid to add these two lines in every method:

String principal = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    MDC.put("username",principal);

So I was thinking to create a custom annotation to get the user and to put it in the MDC log. This way I could just apply this annotation to the methods I need this log, I'm not sure how to accomplish that, could you help me?

Thanks

Use C-macro for this.. No, seriously, why not to use C-preprocessor for this? Just define macro for this two lines using #define and then give file with it to preprocessor. It must work.

UPD. Do it like this:

#define MDCLOG {
    String principal = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    MDC.put("username",principal);
}
public void deleteAccount(Long id) {
    MDCLOG
    accountDao.remove(id);
    List<String> action = (List<String>) MDC.get("action");
    if (action == null)
        action=new ArrayList<String>();
    action.add("Deleted account with id:"+id);
    MDC.put("action", action);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM