Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Docs: not entirely clear what happens if you inject a bean with an unsatisfied requirement #10757

Open
mikehearn opened this issue Apr 23, 2024 · 2 comments

Comments

@mikehearn
Copy link
Contributor

Issue description

From reading the docs I understand that I can add requirements to a bean so that it may not be available at runtime. What's not really clear is what happens if I inject a bean that has an unsatisfied requirement. Is the reference set to null? Is there an exception? If I want to say "give me this bean if it's available, but, not if it isn't" what am I supposed to do here? Presumably injecting lists of interfaces means it just won't appear in the list, but what if I don't need an extra interface and list? Maybe use Optional<BEAN>? The docs seem to think this is obvious but for people who haven't worked with Spring or similar frameworks, it isn't especially obvious.

@alvarosanchez
Copy link
Member

What's not really clear is what happens if I inject a bean that has an unsatisfied requirement. Is the reference set to null? Is there an exception?

A bean that doesn't match its requirements is never created. There is no such bean, and when trying to inject it elsewhere, you will get... NoSuchBeanException (pun intended 😜).

If I want to say "give me this bean if it's available, but, not if it isn't" what am I supposed to do here?

Wrap it in an Optional.

The docs seem to think this is obvious but for people who haven't worked with Spring or similar frameworks, it isn't especially obvious.

Would you please be so kind to send a PR to the exact parts of the docs where you miss this, given my previous answers?

@sdelamo
Copy link
Collaborator

sdelamo commented Apr 24, 2024

If I want to say "give me this bean if it's available, but, not if it isn't" what am I supposed to do here?

Wrap it in an Optional.

or annotate it with @Nullable.

@Controller
class MyController {
    private final ServiceWhichMayNotBeAvailable service;
    MyController(@Nullable ServiceWhichMayNotBeAvailable service) {
        this.service = service;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants