java.lang.String cannot be cast to ……怎么解决?

Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to com.regex.domain.Customer
	at com.regex.service.CustomerService.getCustomer(CustomerService.java:28) ~[classes/:na]
	at com.regex.service.impl.UserDetailsServiceImpl.loadUserByUsername(UserDetailsServiceImpl.java:23) ~[classes/:na]
	at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:93) ~[spring-security-core-5.4.6.jar:5.4.6]
	... 57 common frames omitted
package com.regex.service;

import com.regex.domain.Authority;
import com.regex.domain.Customer;
import com.regex.repository.AuthorityRepository;
import com.regex.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

// 对用户数据结合Redis缓存进行业务处理
@Service
public class CustomerService {
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private AuthorityRepository authorityRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    // 业务控制:使用唯一用户名查询用户信息
    public Customer getCustomer(String username){
        Customer customer = null;
        Object o = redisTemplate.opsForValue().get("customer_"+username);
        //System.out.println(o);
        if(o != null){
            customer = (Customer) o;
            System.out.println(customer);
        }else {
            customer = customerRepository.findByUsername(username);
            if(customer != null){
                redisTemplate.opsForValue().set("customer_"+username, customer);
            }
        }
        return customer;
    }
    // 业务控制:使用为用户名查询权限
    public List<Authority> getCustomerAuthority(String username){
        List<Authority> authorities = null;
        Object o = redisTemplate.opsForValue().get("authorities_"+username);
        if(o != null){
            authorities = (List<Authority>)o;
        }else {
            authorities = authorityRepository.findAuthoritiesByUsername(username);
            if(authorities.size()>0){
                redisTemplate.opsForValue().set("authorities_"+username,authorities);
            }
        }
        return authorities;
    }
}
package com.regex.service.impl;

import com.regex.domain.Authority;
import com.regex.domain.Customer;
import com.regex.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

// 自定义一个UserDetailService接口实现类进行用户认证信息封装
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private CustomerService customerService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 通过业务方法获取用户及权限信息
        Customer customer = customerService.getCustomer(s);
        List<Authority> authorities = customerService.getCustomerAuthority(s);
        // 对用户权限进行封装
        List<SimpleGrantedAuthority> list = authorities.stream()
                .map(authority -> new SimpleGrantedAuthority(authority.getAuthority()))
                .collect(Collectors.toList());
        // 返回封装的UserDetails用户详情类
        if(customer != null){
            UserDetails userDetails =
                    new User(customer.getUsername(),customer.getPassword(),list);
            return userDetails;
        }else {
            // 如果查询的用户不存在(用户名不存在),必须抛出此异常
            throw new UsernameNotFoundException("当前用户不存在!");
        }
    }
}

 

问题解决了!

解决的方式是清楚了redis数据库里面的数据,以及重新将数据导进Navicat,之后重启就没有出现这种问题了。

个人猜测原因可能有以下两种:​​​

之前打错了CustomerService类中第33行代码:

redisTemplate.opsForValue().set("customer_"+username, customer);

错误代码:

redisTemplate.opsForValue().set("customer_"+username, username);

但后来我重试了一遍,却没有问题了!!!

所以还有另一种原因是redis数据库的问题!!!

 

cannot be cast to com.regex.domain.Customer 

25行的是字符串,不能转换为Customer类。

你的类型是 String 类型的,不能强制转换为 Customer 类型。猜测是 json 形式的。所以你需要

JSON.parseObject((String) o, Customer.class)

我这个使用的是 fastJson 的包。所以你的项目里面应该是自带了依赖的。你需要把包导入进来才行。

CustomerService 类的28行customer = (Customer) o;换成

customer =JSON.parseObject(JSON.toJSONString(o), Customer.class);

望采纳! 

25行改为

String val = redisTemplate.opsForValue().get("customer_"+username);

 

项目中引入fastjson依赖,或者添加fastjsonjar包

import com.alibaba.fastjson.JSON;

 

28行改为

customer =JSON.parseObject(val, Customer.class);

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632

非常感谢您使用有问必答服务,为了后续更快速的帮您解决问题,现诚邀您参与有问必答体验反馈。您的建议将会运用到我们的产品优化中,希望能得到您的支持与协助!

速戳参与调研>>>https://t.csdnimg.cn/Kf0y

非常感谢您使用有问必答服务,为了后续更快速的帮您解决问题,现诚邀您参与有问必答体验反馈。您的建议将会运用到我们的产品优化中,希望能得到您的支持与协助!

速戳参与调研>>>https://t.csdnimg.cn/Kf0y