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

Spring配置:原型Bean依赖单例Bean时能否合并两个配置类?

Can I Merge These Two Configuration Classes?

Absolutely! You can definitely combine your two configuration classes into a single one—this is actually a clean, common practice to keep related bean definitions organized in one place, making your codebase easier to maintain.

Here’s what the merged configuration class would look like (using Spring’s preferred method call approach):

@Configuration 
public class CombinedBeanConfig { 
    @Bean 
    public MySingleton mySingleton() { 
        return new MySingleton(); 
    } 

    @Bean 
    @Scope("prototype") 
    public MyPrototype myPrototype() { 
        // Spring ensures this call returns the singleton instance, even if called multiple times
        return new MyPrototype(mySingleton()); 
    } 
}

How does this work?

Spring uses CGLIB proxying for @Configuration classes. When you call a @Bean method from within the same configuration class, Spring doesn’t just execute the method directly—it returns the already created singleton instance (if it exists). That means every new MyPrototype instance will get the same MySingleton bean, just like your original two-config setup.

Alternatively, you can still use @Autowired if you prefer:

If you’re more comfortable with field injection like your original ConfigClassB, this works too in a single configuration class:

@Configuration 
public class CombinedBeanConfig { 
    @Bean 
    public MySingleton mySingleton() { 
        return new MySingleton(); 
    } 

    @Autowired
    private MySingleton mySingleton;

    @Bean 
    @Scope("prototype") 
    public MyPrototype myPrototype() { 
        return new MyPrototype(mySingleton); 
    } 
}

Key Takeaway

Both approaches will behave exactly like your original separate configuration classes:

  • MySingleton remains a singleton (only one instance created for the application context)
  • Every request for MyPrototype creates a new instance, each injected with the same MySingleton bean

Merging them just keeps your bean configuration more centralized and cohesive.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:19:28