com.lrl.abc.service.abc 中的字段 jdbcTemplate 需要类型为“org.springframework.jdbc.core.JdbcTemplate”的 bean,但无法找到

问题描述 投票:0回答:1

我创建了 Spring Boot 应用程序来创建 Restful Api。我在 AWS 上有 Postgres 数据库,因此我想连接到它并执行增删改查操作。 我已经完成了一些文章,但现在遇到了 Jdbc DataSource 错误。以下是代码:

应用程序.属性

spring.datasource.url=jdbc:postgresql://abc.awe.us-east-2.rds.amazonaws.com:5432/test_db
spring.datasource.username=postgres
spring.datasource.password=***********
spring.datasource.driverClassName=org.postgresql.Driver

Abc服务

 @Service
 public class AbcService {
     @Autowired
     private JdbcTemplate jdbcTemplate;

     @Autowired
     public AbcService(JdbcTemplate jdbcTemplate) {
         this.jdbcTemplate = jdbcTemplate;
     }

这样使用

String result = this.jdbcTemplate.queryForObject(
                     "select name from table where id=?",
                     String.class,
                     id
             );

尝试过这样的配置文件

@Configuration
public class DataSourceConfig {

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

我仍然收到以下错误:

 Exception encountered during context initialization - cancelling refresh attempt: 
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean 
with name 'abcService' defined in file 
[/code/build/classes/java/main/com/lrl/abcService/service/abcService.class]: Unsatisfied dependency expressed through constructor parameter 0: 
No qualifying bean of type 'org.springframework.jdbc.core.JdbcTemplate' available: 
expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: 
{}

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in 
com.lrl.abcService.service.AbcService required a bean 
of type 'org.springframework.jdbc.core.JdbcTemplate' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.jdbc.core.JdbcTemplate' in your 
configuration.


你能帮助我这里缺少的东西吗!

java spring postgresql spring-boot spring-jdbc
1个回答
0
投票

有两件事,你有mysql-connector-java依赖吗?另外,您可以尝试设置/硬编码数据源值,例如 dataSource.setURL()。

© www.soinside.com 2019 - 2024. All rights reserved.