Listing 5-58. Profile Java Configuration Example
package com.apress.prospring3.ch5.profile;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ProfileJavaConfigExample {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("kindergarten");
ctx.register(KindergartenConfig.class, HighschoolConfig.class);
ctx.refresh();
FoodProviderService foodProviderService =
ctx.getBean("foodProviderService", FoodProviderService.class);
List<Food> lunchSet = foodProviderService.provideLunchSet();
for (Food food: lunchSet) {
System.out.println("Food: " + food.getName());
}
}
}
In Listing 5-58, we used the AnnotationConfigApplicationContext implementation and its register()
method to register the bean definitions from both the KindergartenConfig and HighschoolConfig classes.
The other code remains the same. Run the program, and you will see the lunch set for kindergarten.
Using the JVM argument spring.profiles.active is the same as the XML example. I'll leave it
to you to try it.
Considerations for Using Profiles
The profiles feature in Spring 3.1 creates another way for developers to manage the application's
running configuration, which used to be done in build tools (e.g., Maven's profile support). Build tools
rely on the arguments passed into the tool to pack the correct configuration/property files into the Java
archive (JAR or WAR depends on the application type) and then deploy to the target environment.
Spring's profile feature lets us as application developers define the profiles by ourselves and activate
them either programmatically or by passing in the JVM argument. By using Spring's profile support, you
can now use the same application archive and deploy to all different environments, by passing in the
correct profiles as an argument during JVM startup. For example, you can have applications with
different profiles such as (dev, hibernate), (prd, jdbc), and so on, with each different combination
representing the running environment (development or production) and the data access library to use
(Hibernate or JDBC). It brings application profile management into the programming side.
But this approach also has its drawbacks. For example, some may argue that putting all the
configuration for different environments into application configuration files or Java classes and
bundling them together will be error prone if not handled carefully (e.g., the administrator forgot to set
the correct JVM argument in their application server environment). Packing files for all profiles together
will also make the package a bit larger than usual. Again, let the application and configuration
requirements drive you to select the approach that best fits your project.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home