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工厂里面的注解
本文档记录了在SpringBoot2.5.8和JDK11环境下,配置COS服务器bean时遇到的问题及解决方案。错误出现在尝试使用`@Configurable`注解来配置bean,导致启动失败。解决办法是将`@Configurable`替换为`@Configuration`,因为后者在容器启动时初始化bean,适合这种场景。了解不同注解的适用范围对于避免类似问题至关重要。

1万+

被折叠的 条评论
为什么被折叠?



