spring-projects / spring-framework

Spring Framework
https://spring.io/projects/spring-framework
Apache License 2.0
56.19k stars 37.96k forks source link

Feature Request: Scoped Bean Injection Control by Bean Creators #33393

Open yonyes opened 4 weeks ago

yonyes commented 4 weeks ago

I propose introducing a feature to Spring Framework that allows developers to specify the packages or classes where their bean can be injected. This feature aims to give bean creators more control over the injection scope, thereby enhancing application modularity and preventing misuse.

Problem Description: Currently, all beans in an application are eligible for autowiring across the entire application. This can lead to beans being used in contexts not intended by their creators, which complicates maintenance and can lead to architectural inconsistencies.

Proposed Feature: Implement a configuration mechanism, potentially through annotations, that enables bean creators to restrict where their beans can be injected. Unlike solutions like @Qualifier, which are controlled by the consumers, this feature would allow creators to define injection boundaries directly.

Use Cases:

Benefits:

I believe this feature would significantly improve developers' control over their applications, making the Spring Framework even more robust for large-scale projects and modular library development.

a-e-tsvetkov commented 3 weeks ago

You can limit visibility of your bean interface with module declaration. You can't inject bean if its interface isn't accessible. Well, technically you can with referencing them by name, but you can't do it by mistake.

yonyes commented 3 weeks ago

You can limit visibility of your bean interface with module declaration. You can't inject bean if its interface isn't accessible. Well, technically you can with referencing them by name, but you can't do it by mistake.

Thank you for suggesting Java module declarations to control bean visibility. While effective at managing package access between modules, the adoption of Java modules is inconsistent, particularly in large or legacy codebases. Moreover, not all Java libraries and frameworks fully support modularization, which can limit their practical use.

It's also important to note that beans in Spring are often autowired by type rather than through interfaces, which Java modules might not sufficiently restrict within the same module. This can lead to broader access than intended, even with modularization in place.

I propose a feature in Spring Framework that allows for granular control over bean injection, directly through Spring configuration. This would enable developers to restrict bean injection both across and within modules, enhancing modularity and preventing unintended bean usage. This feature would support both environments using Java modules and those that do not, helping to maintain clean architectural boundaries and prevent confusion in projects with multiple teams.