如何注入用户名(不是身份验证)?

在我的 spring boot 应用程序中,在我的 rest 控制器中,我成功地注入了一个实例Authentication来获取会话的用户信息。


但是,在所有这些控制器中,我目前调用这样的辅助方法:


@GetMapping

public List<String> getData(Authentication auth) {

    String username = auth.getName().replaceFirst(".*?\\\\", ""); // to remove windows domain name

    // the rest of these methods only use variable `username`, never `auth`

}

如何减少此代码重复?


忽然笑
浏览 168回答 1
1回答

GCT1015

您可以按如下方式创建一个实用程序类,然后您可以UserUtility.getUsername()在任何需要的地方使用它。public class UserUtility {&nbsp; &nbsp; public static String getUsername(){&nbsp; &nbsp; &nbsp; &nbsp; if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return SecurityContextHolder.getContext().getAuthentication().getPrincipal());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java