0

I want to resolve a circular dependency with it.

I am aware that there is a drawback of this annotation namely in case of a bean misconfiguration the error will come to the surface only at invocation time:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Lazy.html

"Please note that such a lazy-resolution proxy will always be injected; if the target dependency does not exist, you will only be able to find out through an exception on invocation. As a consequence, such an injection point results in unintuitive behavior for optional dependencies."

My question is this really a drawback in any sense if I already use the given bean as non-lazy singleton at other parts of application? Which basically proves that the bean itself can be created.

example:

@Component
class A {
  @Autowired
   private B b;
}

@Component
class B {
  @Autowired
  @Lazy
   private A a;
}

@Component
class C {
  @Autowired
   private A a; <- this is the evidence that the bean can be created so it wont fail when injecting it into classB when invoked
}
beatrice
  • 3,684
  • 5
  • 22
  • 49
  • If you are dealing with circular dependency problems, then your problem is not really the injection itself. Keep in mind that [field injection is not recommended](https://stackoverflow.com/a/39892204/10621296) – Jetto Martínez Oct 07 '22 at 14:36
  • The problem is not your annotations or method of injection but the circular dependency. You really should be fixing that and not implement a workaround/hack with `@Lazy`. But that is all IMHO ofcourse. – M. Deinum Oct 07 '22 at 14:42

1 Answers1

0

As long as your configuration is correct, it should work. In some cases, you need circular dependencies and this is the best way that I've found to implement.

Constructor injection is better but won't always work.

Alternatively, you can inject the BeanFactory and fetch in a @PostConstruct or afterPropertiesSet() method, but using @Lazy property injection seems cleaner.