没有可用的 'org.springframework.jdbc.core.JdbcTemplate' 类型的合格 Bean 错误



我正在运行教程.示例 https://developer.ibm.com/tutorials/spring-with-db2-via-jdbc/但是无法让它工作,我不断收到以下错误,不确定如何解决。

没有类型为"org.springframework.jdbc.core.JdbcTemplate"的合格 bean:预计至少有 1 个符合自动连线候选条件的 bean。Dependency annotations: {@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);
}
}

应用程序属性 -

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());
}
}

相关内容

最新更新