|
This version is still in development and is not considered stable yet. For the latest stable version, please use Spring Framework 7.0.5! |
Mixing Component Classes, XML, and Groovy Scripts
It may sometimes be desirable to mix component classes (typically @Configuration
classes), XML configuration files, or Groovy scripts to configure an ApplicationContext
for your tests. For example, if you use XML configuration in production for legacy
reasons, you may decide that you want to use @Configuration classes to configure
specific Spring-managed components for your tests, or vice versa.
Furthermore, some third-party frameworks (such as Spring Boot) provide first-class
support for loading an ApplicationContext from different types of resources
simultaneously (for example, @Configuration classes, XML configuration files, and
Groovy scripts). The Spring Framework, historically, has not supported this for standard
deployments. Consequently, most of the SmartContextLoader implementations that the
Spring Framework delivers in the spring-test module support only one resource type for
each test context. However, this does not mean that you cannot use a mixture of resource
types. One exception to the general rule is that the GenericGroovyXmlContextLoader and
GenericGroovyXmlWebContextLoader support both XML configuration files and Groovy
scripts simultaneously. Furthermore, third-party frameworks may choose to support the
declaration of both classes and locations through @ContextConfiguration, and, with
the standard testing support in the TestContext framework, you have the following options.
If you want to use @Configuration classes and resource locations (for example, XML or
Groovy) to configure your tests, you must pick one as the entry point, and that one must
import or include the other. For example, in a @Configuration class, you can use
@ImportResource to import XML configuration files or Groovy scripts; whereas, in XML or
Groovy scripts, you can include @Configuration classes by using component scanning or
defining them as normal Spring beans. Note that this behavior is semantically equivalent
to how you configure your application in production: In production configuration, you
define either a set of @Configuration classes or a set of XML or Groovy resource
locations from which your production ApplicationContext is loaded, but you still have
the freedom to import or include the other type of configuration.