Repository navigation
Description
Rob Winch opened SPR-13779 and commented
It would be nice to be able to allow Java Configuration to register multiple types of Beans. For example, right now the Spring Security exposes a Java DSL like this:
public void configure(HttpSecurity http) {
http
.formLogin()
}This single invocation (made by the developer configuring Spring Security) should ideally create numerous Beans (i.e. UsernamePasswordAuthenticationFilter, AuthenticationEntryPoint, etc) and expose them to the Spring ApplicationContext.
The key takeaway is that a developer should be able to interact with a DSL where a single invocation creates multiple Beans.
This is something Juergen Hoeller and I spoke about briefly at SpringOne that I would like to get on the roadmap (hopefully for Spring 5).
Updated
To elaborate on my comment below, I think it would be nice if we could do something like this:
class MyDsl {
private boolean addABean;
private boolean addBBean;
// getters /setters
}
class MyDslXmlParser {
MyDsl parse(Document d) {
return createDls(d);
}
}
class MyDslParser {
public void registerBeans(MyDsl dsl, BeanFactory) {
if(dsl.isAddABean()) {
bf.registerBean(new A());
}
if(dsl.isAddBBean()) {
bf.registerBean(new B());
}
}
}I Java Config Users could consume this with:
class JavaConfig {
@Bean
public MyDsl myDsl() {
MyDsl myDsl = new MyDsl();
myDsl.setAddABean(true);
return myDsl;
}
}and MyDslParser.registerBeans would automatically be invoked with the proper arguments.
In XML Config users could consume this with:
<mydsl:mydsl aBean="true" />and MyDslParser.registerBeans would automatically be invoked with the proper arguments.
This would allow the framework to easily support multiple ways of configuring the Beans.
Issue Links:
- Add a functional way to register a bean [SPR-14832] #19398 Add a functional way to register a bean ("depends on")
- Functional bean dependencies tracking [SPR-15417] #19979 Functional bean dependencies tracking ("depends on")
- New controller for Spring MVC using Lambda [SPR-12954] #17546 New controller for Spring MVC using Lambda
- easier framework support for the creation & injection of a bean by its class [SPR-4594] #9271 easier framework support for the creation & injection of a bean by its class
- Provide bean conditional registration capabilities in
BeanRegistrar#21497 Support for conditional registration of functional bean definitions - Provide registerBean variants based on ResolvableType [SPR-15197] #18463 Provide registerBean variants based on ResolvableType
2 votes, 16 watchers
Activity
spring-projects-issues commentedon Aug 10, 2016
Juergen Hoeller commented
Rob Winch, could you sketch the bean registration logic for a use case such as the above? What would it take to register those underlying beans via the
BeanDefinitionRegistry, i.e. viaGenericBeanDefinitionsetup andregisterBeanDefinitioncalls? Ideally, I'd like to provide something more lambda-oriented than that but for a start it'd be good to understand your needs a bit better.spring-projects-issues commentedon Aug 11, 2016
Rob Winch commented
Juergen Hoeller Thanks for reaching out.
I have put together a small (very simplified) sample that demonstrates the use case above. Some of the simplifications are:
Part of the reason I like the idea of using
BeanDefinitions is because they tend to handle circular references better. This will almost certainly improve the user experience when they are using Spring Security since it tends to cause all sorts of circular references. An example of such:Ultimately, I think it would be awesome if somehow I could reuse the Bean Creation logic for both my XML Namespace and Java Configuration. For example, I might first turn the following XML:
into a Java Bean like:
Then I can run the
HttpSecurityobject through the same logic that creates Beans from Java Config DSL (i.e. the code that creates beans from theHttpSecurityobject).Cheers,
Rob
spring-projects-issues commentedon Dec 20, 2016
Janne Valkealahti commented
I think these issues for getting proper programmatic registration of beans can be boiled down to a very simple missing feature, from JavaConfig returning a list of beans.
At compile time if I don't know how many instances of MyBean class I have, I either have to use ImportBeanDefinitionRegistrar which most of a times is a bit useless as it can only access annotation info and some resources or use BFPP's. So many times I've hoped that I could just return List and spring would treat list members as beans.
spring-projects-issues commentedon Jan 4, 2017
Rossen Stoyanchev commented
We have these cases in the MVC Java config:
ViewResolverandHandlerExceptionResolverbeans -- either a default set or the set of instances provided by the application through aWebMvcConfigurer. Currently we use aViewResolverCompositeand aHandlerExceptionResolverCompositeto wrap these sets but it's not ideal with regards to lifecycle methods since we can't be sure if given instances are already beans or not.Optional registration of a
HandlerMappingdepending on static resource and view controller registrations via aWebMvcConfigurer.spring-projects-issues commentedon Jan 7, 2017
Sébastien Deleuze commented
See also my functional Spring Boot draft proposal since I think this use case could take advantage of what is discussed here.
spring-projects-issues commentedon Apr 4, 2017
Juergen Hoeller commented
So is there anything that we need to do for 5.0 still? If yes, could the stakeholders please summarize their current position :-)
spring-projects-issues commentedon Apr 4, 2017
Rob Winch commented
Juergen Hoeller Thanks for reaching out. I chatted with Sébastien Deleuze I don't think this is really solved from my perspective. He is going to see if he can prototype out the example I have above and get back to me.
spring-projects-issues commentedon Apr 14, 2017
Sébastien Deleuze commented
We had a discussion with Rob about his use case. Functional bean registration API is very powerful because it allows to register programmatically beans, using
iforforstatements, but maybe the missing point is how to integrate properly in a JavaConfig based Spring application (typically a Spring Boot one).The most important need I have identified about the feature discussed here is that Spring Framework should provide a way to contribute some beans with the functional bean registration API as part of an application that is using XML or JavaConfig, and I am not sure actually how to do that in order to get it invoked at the right moment of the lifecycle.
To express that differently, the need here is to allow Spring Security and other Spring projects to leverage the powerful/flexible bean registration API for there internals while integrating in Spring Boot application that still leverage JavaConfig for users beans or Spring Boot internals. So it seems to me that we need to have a bridge between JavaConfig and functional bean rehgistration API to use both in the same application. That would be super useful for Spring Boot as well (discussion on this issue shows that there is no easy way to do that currently).
Another important point is how the
MyDslobject will be provided. If we take Spring Securitry example, the DSL is what the user provides using@EnableWebSecurity+WebSecurityConfigurerAdapteroverriden methods. If we take a concrete example, currently Spring Security allows to specify its configuration via a Java DSL that leverage internally@Importto create a few beans +META-INF/spring.factoriesto create object instances that are not beans because of the current limitation of JavaConfig:The purpose of the feature discussed on this issue would be IMO to provide a way for Spring Security to provide a
registerBeansWithFunctionalApimethod that could invoke something likeconfigure(HttpSecurity http)to allow the user to specify his configuration using the Java DSL, and then to perform variouscontext.registerBeaninvocations to register beans consitionnaly based on what the user has register.For example, it would be nice for Spring Security to be able to do that kind of things:
I am not sure at all there is a need for a dedicated annotation for that, but the idea is to provide an extension point that can allow a JavaConfig Spring application to leverage functional bean registration API. Instantiating
ApplicationContextand callingrefresh()would still be manage by JavaConfig.spring-projects-issues commentedon Apr 14, 2017
Janne Valkealahti commented
One of the easiest examples to show what we're missing from a programmatic registration is how Spring Integration javadsl fails. If taking below example which creates gateway and registers it to app context, you can't ever auto-wire it because only hook they have is registerSingleton and that is called only after spring tries to auto-wire beans.
IntegrationFlowBeanPostProcessor.java#L283
spring-projects-issues commentedon Apr 19, 2017
Juergen Hoeller commented
I've done some local tests with straight use of an injected
GenericApplicationContext, and this seems to work fine for me...Anything I'm missing here?
spring-projects-issues commentedon Apr 19, 2017
Janne Valkealahti commented
I've never seen any of our own code to directly use GenericApplicationContext, probably for a good reason as I'd assume it opens a can of worms to all sort of other issues which are potentially impossible to track down.
Lets say that there are multiple
@Configurationclasses which register their own MyOtherBean's and then some other class injects List. I assume there is no way for Spring to know that those specific register methods should be called before possible inject happens for those beans. In this case I assume what would get injected to List is not predictable?Would it be bad to have some sort of an annotation which would instruct context that this specific method will eventually provide/register beans of certain type? Not sure I like this idea myself either but we do have a chicken/egg situation here and all these are really starting to limit what we can do in all other Spring umbrella projects.
spring-projects-issues commentedon Apr 19, 2017
Sébastien Deleuze commented
Juergen Hoeller I made a try with my MiXiT application (which is a Spring Boot + Kotlin application), if I replace
By
I get the following error :
spring-projects-issues commentedon Apr 19, 2017
Juergen Hoeller commented
Janne Valkealahti, Sébastien Deleuze, good points: Such
@Autowired-driven registrations work in general but they might come in too late for other injection points. I'll see what we can do about this, probably enforcing such a callback atBeanDefinitionRegistryPostProcessortime.spring-projects-issues commentedon Sep 4, 2017
Sébastien Deleuze commented
Here is a quick update on the Spring Boot + functional bean registration use case : in addition to
@Autowired-driven registration, the other way to register beans with Boot is via usingApplicationContextInitializerwithSpringApplicationAPI, as described in this comment.When this issue will be fixed, I will check both works with MiXiT application.
spring-projects-issues commentedon Sep 6, 2017
Juergen Hoeller commented
I still don't have a clear enough vision of a dedicated first-class mechanism here, so I'd rather defer this to 5.1. The existing mechanisms remain in place: functional registration works in custom
BeanDefinitionRegistryPostProcessorandApplicationContextInitializerimplementations which can be mixed and matched with configuration classes. There is just no specific callback arrangement for functional registration within configuration classes yet.52 remaining items
sdeleuze commentedon Feb 25, 2025
I just pushed the related modifications and updated the related comment above. Will add more tests to check the behavior before end of the week.
wakingrufus commentedon Feb 26, 2025
Is the plan to have
BeanRegistrarDslbe source-compatible withBeanDefintionDsl? or will there have to be a migration to switch?sdeleuze commentedon Feb 26, 2025
Migration will be required (but easy, both are pretty close).
wakingrufus commentedon Feb 26, 2025
Ok thanks. I'd be happy to help with an openrewrite recipe when the time comes.
Introduce first-class support for programmatic bean registration
Introduce BeanRegistrarDsl
Document programmatic bean registration
sdeleuze commentedon Mar 6, 2025
After a lot of refinements and polish (thanks @jhoeller for your feedback), I have merged this feature that I consider as a first-class support for programmatic bean registration, including with support for Spring AOT optimizations and GraalVM native images. I will likely refine the AOT support in M4 to support more advanced use cases.
See the related reference documentation for more details.
@rwinch As discussed, your original use case of conditional bean registration depending on another bean/DSL is not yet supported, but let's explore what we can do to help you for this use case, I suggest we continue this exploration as part of #21497.
wakingrufus commentedon Mar 6, 2025
🎉 so happy to see this done!
I included a slide showing usage of this new API in my talk yesterday at DevNexus.
Polishing
martinlippert commentedon Mar 12, 2025
Support for this in the
Spring Toolsfor VSCode and Eclipse is underway via spring-projects/spring-tools#1498 and spring-projects/spring-tools#1499.OlgaMaciaszek commentedon Mar 14, 2025
This looks great @sdeleuze. From interface clients autoConfiguration perspective, the ability to also add bean aliases, as currently supported through
BeanDefinitionHolderwould also be important. Could adding this be considered?sdeleuze commentedon Mar 14, 2025
Glad you like it. Should be possible, could you please create a related issue? I will add this in M4.
OlgaMaciaszek commentedon Mar 14, 2025
@sdeleuze here it is: #34599