Activate different profiles in different environments
1. Use @Profile on a Bean
# a bean only active during development but not deployed in production
@Component
@Profile("dev")
public class DevDatasourceConfig
# the component is activated only if dev profile is not active:
@Component
@Profile("!dev")
public class DevDatasourceConfig
# Profiles can also be configured in XML.
<beans profile="dev">
<bean id="devDatasourceConfig" class="org.baeldung.profiles.DevDatasourceConfig" />
</beans>
2.The Default Profile
Spring also provides a way to set the default profile when no other profile is active — by using the spring.profiles.default
property.
Example: Separate Data Source Configurations Using Profiles
# Consider a scenario :
# We have to maintain the data source configuration for both the development and production environments.
public interface DatasourceConfig {
public void setup();
}
@Component
@Profile("dev")
public class DevDatasourceConfig implements DatasourceConfig {
@Override
public void setup() {
System.out.println("Setting up datasource for DEV environment. ");
}
}
@Component
@Profile("production")
public class ProductionDatasourceConfig implements DatasourceConfig {
@Override
public void setup() {
System.out.println("Setting up datasource for PRODUCTION environment. ");
}
}
public class SpringProfilesWithMavenPropertiesIntegrationTest {
@Autowired
DatasourceConfig datasourceConfig;
public void setupDatasource() {
datasourceConfig.setup();
}
}
# When the dev profile is active
Setting up datasource for DEV environment.