如何实现营销人员登录后仅查看名下客户及查询为空问题排查
问题排查与实现方案
一、loggedInUser为null的核心原因
你遇到的null问题90%是方法名大小写不匹配导致的:
- 你的
UserAccountRepository中定义的查询方法是findByUsername(username全小写驼峰) - 但你在控制器中调用的Service方法是
findByUserName(多了大写U,拆成了User+Name)
方法名不匹配会导致Service层调用Repository时无法正确执行查询,自然返回null。
另外还有两个可能的诱因:
- 接口未配置Spring Security拦截,请求为匿名访问时,
authentication.getName()返回的是固定值anonymousUser,数据库中无对应用户 - JWT解析逻辑异常,存入SecurityContext的用户名和数据库
username字段存储的内容不一致,匹配不到用户
二、完整修复实现步骤
1. 修正方法名匹配问题
首先对齐Service层和Repository层的方法名:
// UserAccountService 示例实现 @Service public class UserAccountService { @Autowired private UserAccountRepository userAccountRepository; // 方法名和Repository保持一致,用findByUsername而非findByUserName public User findByUsername(String username) { return userAccountRepository.findByUsername(username); } }
控制器中对应修改调用代码:
User loggedInUser = userRepo.findByUsername(authentication.getName());
2. 补全客户查询逻辑
在CustomerRepository中添加关联查询方法,避免懒加载异常可以加@EntityGraph:
@Repository public interface CustomerRepository extends JpaRepository<Customer, Long> { // 同时加载marketer属性,避免懒加载序列化异常 @EntityGraph(attributePaths = "marketer") List<Customer> findByMarketer(User marketer); }
CustomerAccountService对应封装调用即可。
3. 接口权限加固
在查询接口上增加角色校验注解,确保只有营销人员可以访问:
@PreAuthorize("hasRole('Marketer')") @GetMapping(value="marketers/customers") public List<Customer> getListByMarketerName(){ // 先判空避免空指针 Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || !authentication.isAuthenticated()) { throw new RuntimeException("用户未登录"); } User loggedInUser = userRepo.findByUsername(authentication.getName()); if (loggedInUser == null) { throw new RuntimeException("用户不存在"); } return customerRepo.findByMarketer(loggedInUser); }
同时要确保Spring Security配置中开启了方法级权限校验:@EnableMethodSecurity(Spring Security 6+)或@EnableGlobalMethodSecurity(prePostEnabled = true)(旧版本)。
内容的提问来源于stack exchange,提问作者wizdemonizer
相关产品推荐
相关产品推荐

