栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot配置类注入Bean无效,@Autowired爆红无法导入 排错

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot配置类注入Bean无效,@Autowired爆红无法导入 排错

文章目录
    • 1、环境
    • 2、错误复现
    • 3、解决办法
    • 4、原因

1、环境
  • Spring Boot 2.5.8
  • JDK 11
2、错误复现

场景:我们需要在配置类中配置一个CosServer Bean,并注入到Controller中实现文件上传到COS

配置类:

import com.chatroom.utils.CosServer;
import lombok.Data;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

@Data
@Configurable
public class CosConfiguration {

    @Value("${cos.bucketName}")
    private String bucketName;
    @Value("${cos.secretId}")
    private String secretId;
    @Value("${cos.secretKey}")
    private String secretKey;

    @Bean
    public CosServer createCosServer() {
        return new CosServer(bucketName, secretId, secretKey);
    }
}

Controller
在Controller层中注入CosServer的时候发现报错,且启动不了

3、解决办法

观察配置类我们使用的Configurable注解导包为 :org.springframework.beans.factory.annotation.Configurable;可能不正确

❗将Configurable注解的导包改为 org.springframework.context.annotation.Configuration;即可

4、原因

因为CosServer对象需要在容器启动的时候就需要初始化好,并注入到容器中,供其他地方使用,所以只能使用org.springframework.context.annotation下的Configurable注解,不能使用bean工厂里面的注解

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/880023.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号