Could not autowire. (SpringBoot配置绑定功能)

 当我们使用配置绑定功能时,可能会出现Could not autowire这种错误,原因是因为当我们使用配置绑定功能实现实例创建的时候,不再是new出来,而是SpringBoot自动帮你加载resource文件中配置中的信息,从而创建实例。

所以要解决和我相同的错误只需要将类中的构造方法去掉即可,因为我们不在需要new这个类的实例了。

配置绑定功能的两种实现方式

一、@Component + @ConfigurationProperties(prefix = "resource文件中的配置信息前缀")

以上注解都写在对应创建实例的类中

二、@ConfigurationProperties(prefix = "resource文件中的配置信息前缀")+@EnableConfigurationProperties(创建实例的类的class对象)

第一个注解写在对应创建实例的类中,第二个注解写在标有@Configuration的类中

总结:推荐第二种,因为如果要创建实例的类如果是第三方的,我们只有使用的权限,只能使用第二种方式,所以我们推荐第二种方式。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot 3中出现 "Could not autowire. No beans of 'JdbcTemplate' type found" 错误通常是因为你没有正确配置JdbcTemplate bean。要解决这个问题,你可以按照以下步骤进行操作: 1. 确保你在项目的依赖中添加了正确的JdbcTemplate依赖。你可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> ``` 2. 确保在配置类中使用了`@EnableJdbc`注解,这将启用Spring Boot的JDBC支持。例如: ```java import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; @Configuration @EnableJdbc public class AppConfig { // 注入JdbcTemplate bean @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } } ``` 注意:上述示例假设你已经正确配置了数据源(DataSource)。 3. 确保你在需要使用JdbcTemplate的类中使用了`@Autowired`注解进行自动注入。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository public class MyRepository { private final JdbcTemplate jdbcTemplate; @Autowired public MyRepository(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } // 其他方法... } ``` 完成以上步骤后,重新运行应用程序,应该不再出现 "Could not autowire. No beans of 'JdbcTemplate' type found" 错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fake-WTX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值