gpt4 book ai didi

java - 在 Java 中创建自定义注释

转载 作者:行者123 更新时间:2023-12-01 06:25:57 25 4
gpt4 key购买 nike

我正在向基于 Spring 的应用程序添加一些日志,我想记录每个方法以及正在执行该操作的用户。您可以在下面找到方法示例。

@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);
}

该方法的前两行是通用的,因此我希望避免在每个方法中添加这两行:

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

所以我正在考虑创建一个自定义注释来获取用户并将其放入 MDC 日志中。这样我就可以将此注释应用于我需要此日志的方法,我不知道如何实现这一点,你能帮助我吗?

谢谢

最佳答案

为此使用 C 宏。不,说真的,为什么不为此使用 C 预处理器呢?只需使用 #define 为这两行定义宏,然后将其文件提供给预处理器。它必须有效。

UPD。这样做:

#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);
}

关于java - 在 Java 中创建自定义注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31787289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com