4.6. Using Spring Profiles
Spring profiles allow you to customize the application for working in different environments. Depending on an active profile, you can instantiate different implementations of the same bean and assign different values of application properties.
If a Spring bean has @Profile
annotation, it will be instantiated only when the annotation value matches some active profile. In the following example, SomeDevServiceBean
will be used when dev
profile is active, and SomeProdServiceBean
will be used when the prod
profile is active:
public interface SomeService {
String NAME = "demo_SomeService";
String hello(String input);
}
@Service(SomeService.NAME)
@Profile("dev")
public class SomeDevServiceBean implements SomeService {
@Override
public String hello(String input) {
return "Service stub: hello " + input;
}
}
@Service(SomeService.NAME)
@Profile("prod")
public class SomeProdServiceBean implements SomeService {
@Override
public String hello(String input) {
return "Real service: hello " + input;
}
}
In order to define some profile-specific application properties, create a <profile>-app.properties
(or <profile>-web-app.properties
for web module) file in the same package as the base app.properties
file.
For example, for core module:
com/company/demo/app.properties
com/company/demo/prod-app.properties
For web module:
com/company/demo/web-app.properties
com/company/demo/prod-web-app.properties
The profile-specific file will be loaded right after the base file, so the profile-specific properties will override the properties defined in the base file. In the following example, we define connection to a specific database for the prod
profile:
cuba.dbmsType = postgres
cuba.dataSourceProvider = application
cuba.dataSource.dbName = my-prod-db
cuba.dataSource.host = my-prod-host
cuba.dataSource.username = cuba
cuba.dataSource.password = cuba
The list of active profiles can be set for the application in either of two ways:
-
In
spring.profiles.active
servlet context parameter in theweb.xml
file, for example:<web-app ...> <context-param> <param-name>spring.profiles.active</param-name> <param-value>prod</param-value> </context-param>
-
In
spring.profiles.active
Java system property. For example, when running Uber JAR:java -Dspring.profiles.active=prod -jar app.jar