So many men, so many minds. When we are implementing software for different customers we sometimes need to handle various requirements for the same project. For example Customer A needs SAML authentication and customer B needs LDAP authentication. With Spring Profiles (available from Spring 3.1) we are able to provide a way to segregate parts of our implemented application configuration. This blog will help us to make certain code or rather certain Spring beans only available for specific requirements. For example the example used in this blog can be used to activate the required authentication provider for the provider manager when using Spring Security. Profiles can be configured by annotations and/or by xml. Annotations @Component or @Configuration annotated beans can contain the annotation @Profile to only load them in a certain environment.

public class LDAPAuthentication {
   public LDAPAuthentication() {
      System.out.println("LDAP Authentication set by annotations");

public class SAMLAuthentication {
   public SAMLAuthentication() {
      System.out.println("SAML Authentication set by annotations");


Probably not used anymore in freshly started projects, but it is also possible to make certain Spring beans only available within your XML configuration.

   We use the profile attribute on the beans element to specify the profile.
   Only the child beans are loaded on initialization if the profile is active
<beans profile="ldap">
   <bean class="" />
<beans profile="saml">
   <bean class="" />

Activate correct profile

Of course you are able to combine both configurations, but is should be obvious to choose one configuration to make your code more predictable . Just to show the possibilities we have combined them in one project.In a plain Java application the profiles can be setup by activating the profile in your application context.

public static void main(String[] args) {
   //Create new context to show the XML Spring profile setup
   GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
   //Setting 'ldap' as active profile
   //Load the app-context.xml from the root of the classpath
   //We need to refresh the application because we added a resource
   //Closing the application context to release and destroy all resources and cached beans

   //Creating a new context to show the annotation Spring profile setup
   AnnotationConfigApplicationContext actx = new AnnotationConfigApplicationContext();
   //Setting 'saml' as active profile
   //Scan base package for annotations
   //We need to refresh the application because we added a scan
   //Closing the application context to release and destroy all resources and cached beans

See the following github for the full source of this project: