我应该怎么做才能避免服务层方法中的代码重复?

时间:2019-01-03 16:59:12

标签: java spring spring-boot spring-mvc

我的代码有问题。我使用的方法包括添加,更新等服务类。在每种方法中,我都从身份验证用户名,用户名User Object等中检索身份验证等信息,并使用此信息将新对象添加到数据库中,而无需手动给它们提供令牌登录后。如下图

 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
 UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
 String username = userPrinciple.getUsername();

我在Service类的三种方法中使用此代码。我该怎么做才能减少到使用一次?

2 个答案:

答案 0 :(得分:1)

只需移动

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
String username = userPrinciple.getUsername();

转到单独的方法。

示例:

private String getUserName() {
    Authentication authentication = 
    SecurityContextHolder.getContext().getAuthentication();
    UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
    return userPrinciple.getUsername();
}

答案 1 :(得分:0)

将公共代码/行为重构为一个方法,并在必要时调用该方法。在这种情况下,只需遵循@MZxFK的建议即可。冗余是编写好的代码的开放敌人