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

Spring中@Value注入的Configuration类实例化后属性为null如何解决

问题根本原因
  • 手动实例化Spring托管Bean失效:@Configuration、@Value等Spring注解仅对Spring容器管理的Bean生效,你通过new Blacklist()手动创建的实例不会被Spring处理,属性自然不会注入。
  • 调用方未纳入Spring容器管理:如果Filter类本身没有注册为Spring Bean,就算添加@Autowired注解也不会触发依赖注入。
  • 代码存在低级拼写错误:配置类定义为Blacklist(首字母B大写,l小写),调用时写为BlackList(L大写),类名不匹配也会导致注入失败。
  • 初始化时机错误:直接在类属性定义阶段调用blackList.getRegex(),此时Spring还未完成依赖注入,必然读取到null。
修复步骤

1. 统一配置类代码

建议将配置属性私有化,仅通过Getter暴露:

import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Blacklist {
    @Getter
    @Value("${blacklist.regex:}")
    private String regex;
}

2. 改造Filter类,纳入Spring容器管理

添加@Component注解将Filter注册为Spring Bean,通过@Autowired注入配置类,在@PostConstruct初始化方法中读取属性,保证注入完成后再调用:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@Component
public class Filter {
    @Autowired
    private Blacklist blacklist;

    private String regex;

    @PostConstruct
    public void init() {
        this.regex = blacklist.getRegex();
    }
}

如果是Servlet场景的过滤器,可额外添加@WebFilter(urlPatterns = "/*")配置拦截路径,同时在Spring Boot启动类上添加@ServletComponentScan注解扫描过滤器。

可选优化:使用@ConfigurationProperties更优雅的管理配置

当配置项较多时推荐用配置属性类写法,无需逐个添加@Value注解:

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "blacklist")
public class BlacklistProperties {
    private String regex;
}

使用时直接注入BlacklistProperties即可读取对应配置。

注意事项
  • 确保配置文件放在Spring默认扫描路径下:Spring Boot默认会加载resources目录下的application.properties/application.yml,自定义路径需要额外指定配置文件加载地址。
  • 所有需要用到Spring依赖注入的类都必须注册为Spring Bean,禁止手动new实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 15:15:01