You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 2.2.0.RELEASE以下版本@Value注入失败求助

问题分析与解决方案

嘿,这个问题我之前也碰到过!根源在于你用的Lombok注解和Spring的注入逻辑冲突了,我来给你拆解一下:

为什么会报错?

你在类上添加了@AllArgsConstructor注解,这个Lombok注解会自动生成一个包含所有类字段的构造函数——包括那些用@Value注入的DEFAULT_PageSize、AD_IMAGE_PATH等字段。

Spring创建Bean实例时,会优先采用构造函数注入模式。这时候它会把构造函数里的Integer参数(也就是DEFAULT_PageSize)当成需要从Spring容器中获取的Bean,但你并没有在容器中定义一个java.lang.Integer类型的Bean,所以就出现了那个“找不到类型为Integer的Bean”的错误。

解决方法

这里有几种靠谱的解决方案,你可以选一种适合你的:

方案1:改用@RequiredArgsConstructor(推荐)

这个Lombok注解只会为final修饰的字段或者标注了@NonNull的字段生成构造函数。我们把需要Spring注入的依赖(repository和fileService)加上final修饰,@Value注入的字段不用加final,这样生成的构造函数就不会包含这些配置字段了:

@Service
@Transactional(rollbackOn = Exception.class)
@RequiredArgsConstructor
public class AdServiceImpl implements AdService {
    private final AdRepository repository;
    private final FileService fileService;
    @Value("${app.ad.DefaultPageSize}")
    private Integer DEFAULT_PageSize;
    @Value("${app.ad.ImagePath}")
    private String AD_IMAGE_PATH;
    @Value("${app.ad.ImageUrl}")
    private String AD_IMAGE_URL;
}

方案2:手动编写构造函数

如果不想换Lombok注解,你可以手动编写只包含repository和fileService的构造函数,覆盖@AllArgsConstructor生成的全参构造函数:

@Service
@Transactional(rollbackOn = Exception.class)
@AllArgsConstructor
public class AdServiceImpl implements AdService {
    private AdRepository repository;
    private FileService fileService;
    @Value("${app.ad.DefaultPageSize}")
    private Integer DEFAULT_PageSize;
    @Value("${app.ad.ImagePath}")
    private String AD_IMAGE_PATH;
    @Value("${app.ad.ImageUrl}")
    private String AD_IMAGE_URL;

    // 手动编写构造函数,只注入Spring管理的Bean
    public AdServiceImpl(AdRepository repository, FileService fileService) {
        this.repository = repository;
        this.fileService = fileService;
    }
}

额外提醒

别忘了确认你的app.properties文件里确实存在这些配置项:

app.ad.DefaultPageSize=你的默认页码大小
app.ad.ImagePath=你的图片路径
app.ad.ImageUrl=你的图片URL

如果配置项不存在,即使解决了构造函数的问题,@Value还是会注入失败哦!

内容的提问来源于stack exchange,提问作者Shawn99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:32:21