spring icon indicating copy to clipboard operation
spring copied to clipboard

Wrong bean store used when accessing beans through ApplicationContext

Open peterl1084 opened this issue 7 years ago • 1 comments

There are two views:

A and B

both in ViewScope and both @autowiring their own dependencies.

User navigates from view A to view B. This will begin the process of creating the view scoped bean store for the View B where all corresponding view scoped beans of B will end up into. If one of the dependencies of B further accesses a view scoped bean assigned for B through ApplicationContext the lookup is done from the context still active, from the bean store of View A. This will cause instantiation of B's view scoped bean into the bean store of A's

The following happens

A -> a1, a2, a3 - View A has 3 dependencies: a1, a2, a3 B -> b1, b2 - View B has 2 dependencies, b1, b2 b2 -> b3 - Bean b2 has dependency to b3 that it accesses through ApplicationContext.getBean(b3)

While the navigation is still in progress and view B is not yet fully activated, the lookup done by getBean(b3) takes place from the bean store of A. This will end up creating the bean b3 into the bean store A.

Following will result: A -> a1, a2, a3, b3 B -> b1, b2, (b3)

where b3 exists twice in both contexts (or at least in the context A) depending on various circumstances.

The key point of the issue is that injecting b3 into b2 takes place programmatically from a place where traditional autowiring is not possible. In this case I assume the effective view context active is still A that leads to AppCtx accessing it's bean store rather than view B's corresponding bean store.

Additional strangeness will happen if b3 happens to autowire for example event bus that both views might be using, this is dangerous because in that case it will actually autowire event bus from A's context, rather than B's.

peterl1084 avatar Mar 06 '18 13:03 peterl1084

Is there any ETA on this? It was an unexpected surprise when we found this bug by ourselves. It would be great to know if it will be fixed in the near future, or if we have to replace a lot of getBeans in our code.

brp-olle avatar Apr 15 '19 13:04 brp-olle