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

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

文章目录
    • 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工厂里面的注解

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/920250.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存