有没有办法在Spring Boot中将注释的值传递给我的配置?

时间:2017-10-04 18:47:46

标签: java spring spring-boot annotations spring-config

我有一个配置,它是@Import - 由注释编写。我希望配置可以访问注释上的值。这可能吗?

配置:

@Configuration
public class MyConfig
{
    @Bean
    public CacheManager cacheManager(net.sf.ehcache.CacheManager cacheManager)
    {
        //Get the values in here

        return new EhCacheCacheManager(cacheManager);
    }

    @Bean
    public EhCacheManagerFactoryBean ehcache() {
        EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
        ehCacheManagerFactoryBean.setShared(true);

        return ehCacheManagerFactoryBean;
    }
}

注释

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import(MyConfig.class)
public @interface EnableMyCaches
{
    String value() default "";
    String cacheName() default "my-cache";
}

我如何在配置中获得下面传递的值?

@SpringBootApplication
@EnableMyCaches(cacheName = "the-cache")
public class MyServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyServiceApplication.class, args);
    }
}

2 个答案:

答案 0 :(得分:1)

使用简单的Java反射:

Class c = MyServiceApplication.getClass();
EnableMyCaches enableMyCaches = c.getAnnotation(EnableMyCaches.class);
String value = enableMyCaches.value();

答案 1 :(得分:0)

考虑如何实施@EnableConfigurationProperties之类的内容。

注释包含@Import(EnableConfigurationPropertiesImportSelector.class) which,然后导入ImportBeanDefinitionRegistrar s。这些注册商通过了注释元数据:

public interface ImportBeanDefinitionRegistrar {

    public void registerBeanDefinitions(
            AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry);

}

然后,您可以从注释元数据中获取注释属性:

MultiValueMap<String, Object> attributes = metadata
                .getAllAnnotationAttributes(
                        EnableMyCaches.class.getName(), false);
attributes.get("cacheName");