Enabling Spring Bean for Multiple Profiles

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.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *