2

We use circual dependencies with via constructor injection of @Lazy reference to self type so that we get a way to use local methods with @Transactional and other annotations.

Now we are trying to update to Spring Boot 2.6 which prohibits circular references by default.

Is there a better way to call local methods and get the @Transactional and other annotations respected than the @Lazy self reference?

wilx
  • 17,697
  • 6
  • 59
  • 114
  • 1
    Does this help - [allow circular references](https://stackoverflow.com/a/70073863/17795888)? – Chaosfire Jun 03 '22 at 06:38
  • @Chaosfire I know about the property and we are forced to use it. That is why I am asking my question, if there is a better technique. – wilx Jun 03 '22 at 06:41

1 Answers1

-3

you can use @Resource annotation for injection self

class MyClass {
   @Resource
   private MyClass self;
}

paragraph in spring doc

As of 4.3, @Autowired also considers self references for injection (that is, references back to the bean that is currently injected). Note that self injection is a fallback. Regular dependencies on other components always have precedence. In that sense, self references do not participate in regular candidate selection and are therefore in particular never primary. On the contrary, they always end up as lowest precedence. In practice, you should use self references as a last resort only (for example, for calling other methods on the same instance through the bean’s transactional proxy). Consider factoring out the affected methods to a separate delegate bean in such a scenario. Alternatively, you can use @Resource, which may obtain a proxy back to the current bean by its unique name.

  • As your posted documentation says „use it as last resort“. IMHO using the `@self` is bad style – Daniel Rafael Wosch Jun 03 '22 at 10:31
  • this is question about "how to resolve problem with self injection in existing code" not about how to be better. attention about bad practice - exists in documentation block quote. Another variants - redesign of code – Gannebal Barka Jun 03 '22 at 10:40