Can the configuration classes initialization order in @ContextConfiguration affect?

I am using the @ContextConfiguration annotation to manage configurations in my application. The configurations are created so that they provide only the beans that are displayed by this module. For this reason, some beans that are used by this module are not necessarily imported directly. Example:

 configuration --(use)--> module1 --(cannot @Import)--> database \-(use)--------------------------------> database 

The configuration words use module1 , which requires (but does not have to import directly ) the database configuration. Therefore, configuration also uses the database module.

But it seems that the order in which imports are allowed is rather random. Even if I use

 @ContextConfiguration(classes={DatabaseConfig.class, Module1Config.class}) 

This results in an unspecified failure during initialization ( NoSuchBeanDefinitionException ).

Is there any way to influence beans initialization order? Or should I create configuration overlays that @Import configuration by dependency? But in this case, the same question applies to @Import , since it should provide the order of loading dependencies.

+6
source share
2 answers

This problem seems to be due to the fact that different versions of spring are available at the same time. When the code remained working, only part of @Imports was loaded with the org.springframework.context.annotation.ConfigurationClassParser.collectImports(‌​AnnotationMetadata, Set<Object>, Set<Object>) method. When execution was paused by a breakpoint during parsing, everything worked completely fine.

As soon as several versions of the spring library were cleared, the problem disappeared. (At least he didn't show up again after a dozen or so.)

+1
source

I think you should use the @DependsOn annotation - it is designed specifically for such cases.

0
source

Source: https://habr.com/ru/post/955979/


All Articles