Grails Goodness: Conditionally Load Beans in Java Configuration Based on Grails Environment
Join the DZone community and get the full member experience.
Join For FreeIn 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?
It turns out this is not so hard to achieve. We must implement the matches
method from the Condition
interface from the org.springframework.context.annotation
package. Next we create a new annotation interface where we delegate basically to our implementation class.
Let's start with writing an implementation for the Condition
interface:
// File: src/groovy/com/mrhaki/grails/context/annotation/GrailsEnvCondition.groovy package com.mrhaki.grails.context.annotation import grails.util.Environment import org.springframework.context.annotation.Condition import org.springframework.context.annotation.ConditionContext import org.springframework.core.type.AnnotatedTypeMetadata import org.springframework.util.Assert import org.springframework.util.MultiValueMap /** * <p>{@link Condition} that matches based on the value of * a {@link GrailsEnv @GrailsEnv} annotation.</p> * * <p>The value of the current Grails environment is compared to given * Grails environments set via the {@link GrailsEnv @GrailsEnv} annotation.</p> * * @author Hubert A. Klein Ikkink aka mrhaki * @see GrailsEnv */ class GrailsEnvCondition implements Condition { @Override public boolean matches(final ConditionContext context, final AnnotatedTypeMetadata metadata) { final MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(GrailsEnv.class.name) if (attributes != null) { final List<String> value = attributes.get('value') return value ? value.any { acceptsEnvironments(it) } : false } return true } protected boolean acceptsEnvironments(final String... environments) { Assert.notEmpty(environments, "Must specify at least one environment") for (environment in environments) { if (isNegateEnvironment(environment)) { if (!isProfileActive(environment[1..-1])) { return true } } else if (isProfileActive(environment)) { return true } } return false } private boolean isNegateEnvironment(final String environment) { environment != null && environment.length() > 0 && environment[0] == '!' } protected boolean isProfileActive(final String profile) { validateEnvironment(profile); final String currentEnvironment = Environment.current.name profile == currentEnvironment } protected void validateEnvironment(final String environment) { if (!environment || environment.allWhitespace) { throw new IllegalArgumentException("Invalid environment [$environment]: must contain text"); } if (environment[0] == '!') { throw new IllegalArgumentException("Invalid environment [$environment]: must not begin with ! operator"); } } }
Next we create a new annotation @GrailsEnv
. The annotation will accept a String
value or an array of String
values with the name(s) of the Grails environments the bean must be registered for or excluded from:
// File: src/java/com/mrhaki/grails/context/annotation/GrailsEnv.java package com.mrhaki.grails.context.annotation; import org.springframework.context.annotation.Conditional; import java.lang.annotation.*; /** * <p>Indicates that a component is eligible for registration when one * or more {@linkplain #value specified Grails environments} are active.</p> * * <p>The Grails environment can be set via the Java system property * <em>grails.env</em>.</p> * * <p>The {@code @GrailsEnv} annotation may be used in any of the following ways: * <ul> * <li>as a type-level annotation on any class directly or indirectly annotated with * {@code @Component}, * including {@link org.springframework.context.annotation.Configuration @Configuration} classes</li> * <li>as a meta-annotation, for the purpose of composing custom stereotype annotations</li> * <li>as a method-level annotation on * any {@link org.springframework.context.annotation.Bean @Bean} method</li> * </ul> * * <p>If a {@code @Configuration} class is marked with {@code @GrailEnv}, * all of the {@code @Bean} methods and * {@link org.springframework.context.annotation.Import @Import} annotations associated with that class * will be bypassed unless one or more of the specified Grails environments are active.</p> * * <p>If a given Grails environment is prefixed with the NOT operator ({@code !}), * the annotated beans or components will be registered if the Grails environment * is <em>not</em> active. e.g., for {@code @GrailsEnv("!production")}, registration will occur * if Grails environment 'production' is not active.</p> * * <p>If the {@code @GrailsEnv} annotation is omitted, registration will occur, regardless * of which Grails environment is active. * * @author Hubert A. Klein Ikkink aka mrhaki * @see org.springframework.context.annotation.Profile * @see com.mrhaki.grails.annotation.context.GrailsEnvCondition */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) @Conditional(GrailsEnvCondition.class) public @interface GrailsEnv { /** * Annotation attribute value to set Grails environments. * Use an array of String value to determine Grails environments * or use a single String value (is automatically put in array). * Environment maybe prefixed with {@code !} to register component when environment * is NOT active. */ String[] value(); }
We can use our new annotation in a Spring Java configuration class. The following sample shows different values for the @GrailsEnv
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 com.mrhaki.grails.context.annotation.GrailsEnv import org.springframework.context.annotation.* @Configuration class BeansConfiguration { // Load for Grails environments // development or test @Bean @GrailsEnv(['development', 'test']) Sample sampleBean() { new Sample('sampleBean') } // Load for every Grails environment NOT // being production. @Bean @GrailsEnv('!production') Sample sample() { new Sample('sample') } // Load for custom environment name qa. @Bean @GrailsEnv('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 import com.mrhaki.grails.context.annotation.GrailsEnv import org.springframework.stereotype.Component @Component @GrailsEnv('development') class Person { String name String email }
The implementation for GrailsEnv
and GrailsEnvCondition
is based on the existing Spring classes Profile
and ProfileCondition
.
Code written with Grails 2.4.2.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Micro Frontends on Monorepo With Remote State Management
-
Fun Is the Glue That Makes Everything Stick, Also the OCP
-
Working on an Unfamiliar Codebase
-
Integration Architecture Guiding Principles, A Reference
Comments