java - 没有“org.springframework.jdbc.core.JdbcTemplate”类型的合格 bean 可用错误
问题描述
我正在运行https://developer.ibm.com/tutorials/spring-with-db2-via-jdbc/上的 tutorial.example 但无法使其正常工作,我不断收到以下错误并且不确定如何修复.
没有可用的“org.springframework.jdbc.core.JdbcTemplate”类型的合格 bean:预计至少有 1 个有资格作为自动装配候选者的 bean。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}'
本教程中没有提到与设置 bean 无关,所以我不确定我是否应该断开它来修复它,或者我只是犯了一个错误。
我的应用程序类 -
@SpringBootApplication
public class SBApplication {
public static void main(String[] args) {
SpringApplication.run(SBApplication.class, args);
}
}
示例休息控制器 -
package application.rest.v1;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
import main.java.application.jdbc.*;
@RestController
public class Example {
@Autowired
JdbcTemplate jdbcTemplate;
@RequestMapping("test")
public @ResponseBody ResponseEntity<String> example() {
List<String> list = new ArrayList<>();
list.add("Table data...");
jdbcTemplate.query(
"SELECT * FROM things", new Object[]{},
(rs,rowNum) -> new Things(rs.getLong("id"), rs.getString("name")))
.forEach(thing -> list.add(thing.toString()));
return new ResponseEntity<String>(list.toString(), HttpStatus.OK);
}
}
应用程序.properties -
spring.datasource.url=jdbc:imdb://xxxx.xxx.xxxx/xxxx
spring.datasource.username=xxxxxxx
spring.datasource.password=xxxx
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
另外,我没有连接到教程中建议的 DB2 实例,而是连接到我自己的实例。
解决方案
我相信您缺少应该在配置JdbcTemplate
中配置的部分。在使用spring boot
时,可以通过@Configuration
类上的注解来实现。您的典型配置如下所示
@Configuration
public class WebAppConfig {
@Bean(name = "appDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "applicationJdbcTemplate")
public JdbcTemplate applicationDataConnection(){
return new JdbcTemplate(dataSource());
}
}
推荐阅读
- r - 使用调查包循环遍历列并根据条件打印比例或均值表
- r - 为什么 R 会有这样的行为?
- string - 从两个括号之间提取数字
- parsing - 使用 java 8 解析 LocalDateTime 的问题
- elasticsearch - Percolate query alternative for given use case
- ubuntu-14.04 - Python3.6 No module named '_curses'
- dbeaver - How do I enable or configure "Code Folding" and Side-by-Side Text Compare in DBeaver?
- python - 您可以在 TensorFlow/Keras 顺序网络中为多个输出设置目标吗
- kubernetes - K8S Fabric8 API + deploy、pod 和 service 一口气?
- list - 在列表中的每 n 个元素之后输出 y 元素