Profiles-based Bean configuration

Profiles can also be used to define different beans or different bean configurations in different environments. All classes marked with @Component or @Configuration can also be marked with an additional @Profile annotation to specify the profile in which the bean or configuration is enabled.

Let's consider an example. An application needs different caches enabled in different environments. In the dev environment, it uses a very simple cache. In production, we would want to use a distributed cache. This can be implemented using profiles.

The following bean shows the configuration enabled in a dev environment:

    @Profile("dev")
@Configuration
public class DevSpecificConfiguration {
@Bean
public String cache() {
return "Dev Cache Configuration";
}
}

The following bean shows the configuration enabled in a production environment:

    @Profile("prod")
@Configuration
public class ProdSpecificConfiguration {
@Bean
public String cache() {
return "Production Cache Configuration - Distributed Cache";
}
}

Based on the active profile configured, the respective configuration is picked up. Note that we are not really configuring a distributed cache in this example. We are returning a simple string to illustrate that profiles can be used to implement these kinds of variations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset