Conditionally load beans in Spring using XML configuration

Let’s say you want to load a different bean while testing and another one in production.

You can use Spring Expression Language to achieve this task.

The following configuration sets up a “mainBean” composed of a “subBean”. The sub bean could be either “prodSubBean” in your production environment or a “testSubBean” in your testing environment.

The decision is made based on the SYS_ENV_VAR variable which is a system property taken from your system environment.

The important thing to note is that we have to set the “searchSystemEnvironment” flag to true (so that Spring can see system variables).

Also, we don’t want Spring to fail when the SYS_ENV_VAR property isn’t set. Hence, we set both “ignoreUnresolvablePlaceholders" and “ignoreResourceNotFound” flags to true.

We have made the testSubBean the child of prodSubBean just in case we want to inherit most production properties and only change some.
Also the Java TestSubBean class is a sub-class of ProdSubBean for the same reason.