Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Spring Enable Annotation with Selectors
package enableannot.selector;
import org.springframework.context.annotation.Import;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import(SomeBeanConfigurationSelector.class)
public @interface EnableSomeBeansSelector {
String criteria() default "default";
}
package enableannot.selector;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
public class SomeBeanConfigurationSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
AnnotationAttributes attributes =
AnnotationAttributes.fromMap(
importingClassMetadata.getAnnotationAttributes(EnableSomeBeansSelector.class.getName(), false));
String criteria = attributes.getString("criteria");
if (criteria.equals("default")) {
return new String[]{"enableannot.selector.SomeBeanConfigurationDefault"};
}else {
return new String[]{"enableannot.selector.SomeBeanConfigurationType1"};
}
}
}
package enableannot.selector;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class TestEnableWithSelectorAnnotationsType1 {
@Autowired
private String aBean;
@Test
public void testInjectedBean() {
assertThat(aBean, equalTo("Type1"));
}
@EnableSomeBeansSelector(criteria = "type1")
@Configuration
public static class SpringConfig {}
}
@Configuration
class SomeBeanConfigurationType1 {
@Bean
public String aBean() {
return "Type1";
}
}
@Configuration
class SomeBeanConfigurationDefault {
@Bean
public String aBean() {
return "Default";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.