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

Spring中获取Bean属性修改后的值:我的实现方式是否正确?

问题分析与解决方案

一、核心错误:Bean注册方式不正确

你给CustomBean标注了@Configuration注解,这是错误的用法。@Configuration是用来标记Spring配置类的注解,不能直接用来标记普通的Bean类。这种错误的注解方式会导致Spring无法将CustomBean正确识别为容器管理的Bean,后续注入的实例可能并非容器维护的单例对象,直接导致属性修改后无法在其他地方读取到。

二、正确的Bean注册方式

有两种常用的正确注册方式:

  • 方式1:给CustomBean添加@Component注解,让Spring自动扫描并注册为Bean:
@Component
public class CustomBean{
    private String key;
    
    // getter和setter方法
    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }
}
  • 方式2:编写独立的配置类,通过@Bean方法注册CustomBean:
@Configuration
public class BeanConfig {
    @Bean
    public CustomBean customBean() {
        return new CustomBean();
    }
}

三、属性修改后获取为null的排查点

  1. 确认Class1的methodCall1方法中确实执行了customBean.setKey(xxx)的赋值逻辑,且传入的赋值参数不为null,避免因赋值逻辑未执行导致属性仍为null。
  2. 检查代码拼写错误:你写的methdoCall2是拼写错误,正确应为methodCall2,如果方法名错误,Class2根本无法接收到修改后的Bean实例。
  3. 确保MyClass本身是Spring管理的Bean(比如添加@Component、@Service等注解),否则@Autowired注入不会生效,你使用的customBean本身就是null,后续修改自然无效。

四、关于单例Bean属性修改的说明

Spring默认的Bean是单例模式,只要是同一个Spring容器内的Bean实例,修改属性后其他地方注入的同一个实例应该能读取到修改后的值。所以只要Bean注册正确、相关组件都由Spring管理,这种修改后获取属性的方式本身是可行的,但要注意线程安全问题——如果多个线程同时修改或读取该属性,可能出现数据不一致的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 03:46:01