Search

Dark theme | Light theme

August 5, 2014

Grails Goodness: Conditionally Load Beans in Java Configuration Based on Grails Environment

UPDATE: the original blog post shows an implementation for a @GrailsEnv annotation to load beans based on the current Grails environment, but it turns out the @Profile annotation from Spring also works perfectly fine in Grails! Grails will set the current environment name as an active Spring profile, so it is even easier to load beans based on the current Grails environment.

In a previous post we saw that we can use Spring's Java configuration feature to load beans in our Grails application. We can use the @Profile annotation to conditionally load beans based on the currently active Spring profile. We can for example use the Java system property spring.profiles.active when we start the Grails application to make a profile active. But wouldn't it be nice if we could use the Grails environment setting to conditionally load beans from a Java configuration? As it turns out Grails already set the current Grails environment name as the active profile for the Grails application. So we can simply use @Profile in our configuration or component classes, like in a non-Grails Spring application.

We can use the @Profile annotation in a Spring Java configuration class. The following sample shows different values for the @Profile annotation. The annotation is applied to methods in the sample code, but can also be applied to a class.

// File: src/groovy/com/mrhaki/grails/configuration/BeansConfiguration.groovy
package com.mrhaki.grails.configuration

import org.springframework.context.annotation.*

@Configuration
class BeansConfiguration {

    // Load for Grails environments 
    // development or test
    @Bean
    @Profile(['development', 'test'])
    Sample sampleBean() {
        new Sample('sampleBean')
    }

    // Load for every Grails environment NOT
    // being production.
    @Bean
    @Profile('!production')
    Sample sample() {
        new Sample('sample')
    }

    // Load for custom environment name qa.
    @Bean
    @Profile('qa')
    Sample sampleQA() {
        new Sample('QA')
    }

}

We can also use the annotation for classes that are annotated with the @Component annotation:

// File: src/groovy/com/mrhaki/grails/Person.groovy
package com.mrhaki.grails

import org.springframework.stereotype.Component
import org.springframework.context.annotation.Profile

@Component
@Profile('development')
class Person {
    String name
    String email
}

Code written with Grails 2.4.2.