Skip to content

Lazy annotation throws exception if non-required bean does not exist #27649

Closed
@nytro77

Description

@nytro77

Affects: 5.3.12


A bean is defined in a @Configuration class that has a @Profile annotation, so the bean only exists under certain conditions.

In another bean a setter is annotated with @Autowired(required = false) for that bean.
If the bean exists it should be injected. If not, then not much to do about that.
The code will check if the bean is injected (not null) and take appropriate actions.

Now for the problem. If the bean does exist, it needs to be lazy loaded to avoid circular dependency issues.
So, the setter is annotated with @Lazy annotation.
The lazy annotation causes exception "Optional dependency not present for lazy injection point" if the non-required bean does not exist.

The exception says exactly whats happening, so perhaps this is by design then?
I cannot tell from the documentation if this is a use case that is expected to work or not.

In addition to its role for component initialization, you can also place the @lazy annotation on injection points marked with @Autowired or @Inject. In this context, it leads to the injection of a lazy-resolution proxy

Perhaps this behaviour can be changed to lazy load the injection of the non-required bean if it is actually available, and if not then just ignore the @Lazy annotation since the @Autowired annotation itself did nothing?

The problem is reproduced in this GitHub project: https://github.com/nytro77/spring-lazy-bug

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)status: backportedAn issue that has been backported to maintenance branchestype: documentationA documentation task

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions