我在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/