Enabling Spring Bean for Multiple Profiles

Published on March 13, 2015 by

This is going to be a quick one. I just want to show you how one can¬†define a bean in Spring Framework¬†for multiple profiles. That is, the bean will be “active” if the active profile is one in a given list. This is for example useful if you want different beans to be available at runtime depending on the environment in which the application is deployed. An example of this is a TextEncryptor; you might not want to encrypt data on your development machine, because you might want to be able to read the data within the database without having to decrypt it. On the contrary, in this example, you would want to encrypt data in staging and production environments for security purposes. Such a situation can be handled by using the @Profile annotation together with the @Bean annotation, as in the below example.

@Configuration
public class SecurityConfig {
    @Profile("development")
    @Bean
    public TextEncryptor textEncryptorNoOp() {
        return Encryptors.noOpText();
    }

    @Profile({ "production", "staging" })
    @Bean
    public TextEncryptor textEncryptor() {
        return Encryptors.queryableText("password", "salt");
    }
}

Notice that the return types of both beans are the same. When we request a bean of type TextEncryptor (e.g. by using the @Autowired annotation), we will not get an error if we do not use a qualifier, because Spring will know which one to use if an active Spring profile is defined, e.g. via -Dspring.profiles.active=”development”. Also notice that the @Profile annotation lets us pass an array of strings, which can be seen in the annotation’s source code:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Conditional({ProfileCondition.class})
public @interface Profile {
    String[] value();
}

The result in this example is that the noOpText encryptor will be used when the active Spring profile is development, and the queryableText encryptor will be used when the active profile is either staging or production. I personally use Java configuration, but this can also be done with XML.

Featured

Learn Spring Framework today!

Take an online course and become a Spring Framework champion!

Here is what is covered:

  • The Spring Framework basics, including Spring MVC
  • How to work with JDBC and MySQL (in the context of Spring)
  • Build real applications step by step
  • A detailed walkthrough of Spring's core concepts
  • ... and much more!
Spring Framework logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

Leave a Reply

Your e-mail address will not be published.