As Java projects pass from development into production it is sometimes necessary to use different suites of project dependencies and settings, loaded as a profile. In a typical Spring project this can be achieved following a project structure such as:
packagecom.diffblue.loader;// Example interface.publicinterfaceLoader {StringgetMessage();}
Another class loader.MyLoader implements that interface,
packagecom.diffblue.loader;/*** Simple implementation of a loader.*/publicclassMyLoaderimplementsLoader {privatefinalString message;publicMyLoader(String message) { this.message = message; }publicStringgetMessage() {return message; }}
which is used to supply the loader.Loader interface.
This is done in a class config.ProductionConfig where the user has the possibility to configure the loader by using the @Configuration and @Profile() annotations:
packagecom.diffblue.config;importcom.diffblue.loader.Loader;importcom.diffblue.loader.MyLoader;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Profile;/*** Load a "production" loader when we're not* using the test-scenario profile.*/@Configuration@Profile("!test-scenario")publicclassProductionConfig {@BeanpublicLoadergetLoader() {returnnewMyLoader("production"); }}
The class config.ProductionConfig should be annotated with @Profile("!test-scenario") in production mode:
When using IntelliJ, the Spring profile in use must be declared in Run > Edit Configurations > VM Options:
In development mode, the annotation @Profile("test-scenario"), should be used in a class config.TestConfig placed in the test directory:
packagecom.diffblue.config;importcom.diffblue.loader.Loader;importcom.diffblue.loader.MyLoader;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.ComponentScan;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Profile;/*** Load a "test" loader when we are using the test-scenario profile.*/@Configuration@ComponentScan@Profile("test-scenario")publicclassTestConfig {@BeanpublicLoadergetLoader() {returnnewMyLoader("test"); }}
which configures a test loader through the loader.TestLoader also placed in the test directory
packagecom.diffblue.loader;importorg.springframework.context.annotation.Profile;/*** Simple implementation of a loader.*/@Profile("test-scenario")publicclassTestLoaderimplementsLoader {privatefinalString message ="static-test-loader";publicStringgetMessage() {return message; }}
These two classes are placed in the test directory in order to be isolated from a run in the production mode.
To use a specific profile in development mode, the --active-profiles option must be used: