java - 数据库对象持久化后反序列化无法转换为源类 : ClassCastException: TestDomain cannot be cast to TestDomain

标签 java spring spring-session

我在spring-session中遇到以下问题:

@RestController
public class TestService {

    @Autowired
    private SessionRepository sessionRepository;

    @GetMapping("/test")
    public void test() {
        Session session = sessionRepository.createSession();
        TestDomain testDomain = new TestDomain("a", 1);
        session.setAttribute(session.getId(), testDomain);
        sessionRepository.save(session);

        Session session1 = sessionRepository.getSession(session.getId());
        Object testDomainObj = session1.getAttribute(session1.getId());
        // I wonder why TestDomainObj is not an instance of TestDomain??
        System.out.println("Does testDomainObj from session represent the instance of TestDomain class: " + (testDomainObj instanceof TestDomain));

        // java.lang.ClassCastException: com.example.demo.TestDomain cannot be cast to com.example.demo.TestDomain
        TestDomain testDomain1 = (TestDomain) testDomainObj;
        System.out.println(testDomain1);
    }
}

我尝试搜索,发现得到testDomainObj后发现它是Object类的实例。因此,很明显,反序列化的对象丢失了其元信息。

我像这样配置了JdbcOperationsSessionRepository:

@Configuration
public class AppConfig {
    @Bean
    SessionRepository sessionFactoryBean(JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager) {
        return new JdbcOperationsSessionRepository(jdbcTemplate, transactionManager);
    }
}

并在application.properties中激活它:

spring.session.store-type=jdbc
spring.session.jdbc.initializer.enabled=true

执行sessionRepository.save(session);后,最后一件事testDomain对象已保存在数据库中;

如何理解和应对这个问题?

最佳答案

您遇到此问题是因为您手动注册 JdbcOperationsSessionRepository bean,而不是重用 Spring Session JDBC 配置工具,即 @EnableJdbcHttpSession。请参阅the relevant code in JdbcHttpSessionConfiguration .

Spring Boot 通过为 Spring Session 提供自动配置支持,使这一切变得更加容易,因此您甚至不需要使用 @EnableJdbcHttpSession。只需将 spring.session.store-type=jdbc 添加到配置属性即可为您处理一切。

关于java - 数据库对象持久化后反序列化无法转换为源类 : ClassCastException: TestDomain cannot be cast to TestDomain,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49005552/

相关文章:

java.beans.PropertyEditorManager.findEditor(Locale.class) 在 spring 中返回 null

java - spring - 同时使用简单的 SimpleUrlHandlerMapping 和 AnnotationMapping

java - 带有 Dynomite 的自定义 spring-session 存储库 Redis

java - spring-boot 1.3-M5 oauth2 SSO 不适用于 spring-session?

java - 为什么要尝试/捕获可抛出的东西?

java - 这段代码如何用 for 循环形成 z 形状?

java - 给定LocalDate时如何获得一天的结束?

java - 使用用户定义 View 的 Spring MVC 3 用户定义异常处理

java - 使用 .htaccess 保护 .jar?

spring - Spring Session 如何在单个浏览器中支持多个 session ?