Exploring dependency override in Spring

Well, the problem is related to the way we have defined the fooBar bean in our BaseConfig.

Let’s take a look at it:The dependencies are resolved inside the factory method.

When using this kind of dependency resolution Spring uses the same context where the dependency was defined to resolve the bean.

Therefore, Spring uses the bar bean defined in the parent context.

However, in Spring we can also specify our bean dependencies using method arguments:That way, the Spring dependency resolution happens before calling the factory method and the beans are resolved using the context which contains the bean definition (in our case, the child context because we have the exported definition).

Using this mechanism, the test passes!ConclusionWe have seen that it seems to be feasible to analyse the whole dependency graph for a bean and automatically export the definition of the dependant ones to the child context.

The objective of the experiment was to be able to reduce the amount of code we have to write when overriding beans in child contexts.

Sometimes we end up overriding lots of stuff just because we want to have a single bean that is used across many others.

Probably still some conscious tests are needed to check if there is any undesired behaviour with this approach, but it seems to be a good starting point.

Let me know your thoughts!.. More details

Leave a Reply