Skip to content

Lambda-based consumption of an ObjectProvider's object when available [SPR-16001] #20550

Closed

Description

@spring-projects-issues

Andy Wilkinson opened SPR-16001 and commented

In a similar vein to #19474, I just wrote the following:

@Bean
public HttpHandler httpHandler(
		ObjectProvider<WebSessionManager> webSessionManagerProvider) {
	WebHttpHandlerBuilder builder = WebHttpHandlerBuilder
			.applicationContext(this.applicationContext);
	WebSessionManager webSessionManager = webSessionManagerProvider
			.getIfAvailable();
	if (webSessionManager != null) {
		builder.sessionManager(webSessionManager);
	}
	return builder.build();
}

I'd prefer to avoid the local variable and null check. Something like this:

@Bean
public HttpHandler httpHandler(
		ObjectProvider<WebSessionManager> webSessionManagerProvider) {
	WebHttpHandlerBuilder builder = WebHttpHandlerBuilder
			.applicationContext(this.applicationContext);
	webSessionManagerProvider.consumeIfAvailable(
			(webSessionManager) -> builder.sessionManager(webSessionManager));
	return builder.build();
}

Affects: 5.0 RC4

Issue Links:

Referenced from: commits e927cae

Activity

  1. spring-projects-issues commented on Sep 25, 2017

    @spring-projects-issues
    CollaboratorAuthor

    Juergen Hoeller commented

    I guess you could write this using Optional already:

    Optional.ofNullable(webSessionManagerProvider.getIfAvailable()).ifPresent(
            (webSessionManager) -> builder.sessionManager(webSessionManager));
    

    So effectively, this is about syntactic sugar for that kind of code? With ObjectProvider either providing an Optional return variant or, along the lines of your sketch, an ifAvailable(Consumer) convenience method directly?

  2. spring-projects-issues commented on Sep 25, 2017

    @spring-projects-issues
    CollaboratorAuthor

    Juergen Hoeller commented

    I've introduced corresponding ifAvailable(Consumer) and ifUnique(Consumer) variants, along the lines of Optional.ifPresent(Consumer).

  3. spring-projects-issues commented on Sep 26, 2017

    @spring-projects-issues
    CollaboratorAuthor

    Andy Wilkinson commented

    Thanks!

  4. added
    type: enhancement
    in: core
    on Jan 11, 2019
  5. added this to the 5.0 GA milestone on Jan 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

in: coretype: enhancement

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions