Spring Data Cassandra 2.0.5中CqlTemplate注入失败问题咨询
我刚帮你梳理清楚这个问题了——在Spring Data Cassandra 2.x(对应Spring Boot 2.0.x系列)版本里,CqlTemplate的自动配置逻辑确实有变更:旧版本会默认把CqlTemplate实例注册到Spring容器中,但新版本不再这么做,这就是你用@Autowired注入时抛出UnsatisfiedDependencyException的核心原因。
下面是具体的解决步骤,亲测有效:
步骤1:显式注册CqlTemplate Bean
不管你是用自定义的Cassandra配置类,还是依赖Spring Boot的自动配置,都需要手动声明CqlTemplate的Bean。如果是自定义配置类,写法如下:@Configuration public class CassandraConfig extends AbstractCassandraConfiguration { // 重写必要的配置方法,比如Keyspace、ContactPoints等 @Override protected String getKeyspaceName() { return "your_target_keyspace"; } @Override protected String getContactPoints() { return "localhost"; // 你的Cassandra节点地址 } @Override protected int getPort() { return 9042; // Cassandra端口 } // 关键:显式创建CqlTemplate Bean,依赖已配置好的Session @Bean public CqlTemplate cqlTemplate(Session session) { return new CqlTemplate(session); } }如果你用的是Spring Boot自动配置(仅通过
application.properties/application.yml配置Cassandra参数),只需要单独加一个配置类来注册CqlTemplate即可,不需要继承AbstractCassandraConfiguration:@Configuration public class CqlTemplateConfig { @Bean public CqlTemplate cqlTemplate(Session session) { return new CqlTemplate(session); } }步骤2:正确注入CqlOperations或CqlTemplate
现在容器里已经有了CqlTemplate实例,你可以放心注入CqlOperations接口(推荐面向接口编程)或者CqlTemplate实现类了。这里更推荐用构造方法注入,符合Spring依赖注入的最佳实践:@Service public class YourCassandraService { private final CqlOperations cqlOperations; // 构造方法注入,无需@Autowired(Spring 4.3+支持) public YourCassandraService(CqlOperations cqlOperations) { this.cqlOperations = cqlOperations; } // 接下来就可以用cqlOperations执行CQL语句了 public void someDatabaseOperation() { String cql = "SELECT * FROM your_table WHERE id = ?"; // 示例查询 YourEntity entity = cqlOperations.queryForObject(cql, new Object[]{1}, YourEntity.class); } }补充说明
新版本中Spring Data Cassandra更偏向于使用CassandraTemplate(提供了更多ORM相关的能力),但如果你确实需要原生CQL操作的CqlOperations/CqlTemplate,上面的方法完全适用。
内容的提问来源于stack exchange,提问作者Marco Massenzio

