Spring配置:原型Bean依赖单例Bean时能否合并两个配置类?
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:
MySingletonremains a singleton (only one instance created for the application context)- Every request for
MyPrototypecreates a new instance, each injected with the sameMySingletonbean
Merging them just keeps your bean configuration more centralized and cohesive.
内容的提问来源于stack exchange,提问作者hublo

