繁体   English   中英

有什么办法可以在Spring Boot中将注释的值传递给我的配置?

[英]Is there any way to pass an annotation's values to my config in Spring Boot?

我有一个配置,它是@Import 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);
    }
}

使用简单的Java反射:

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

考虑如何实现@EnableConfigurationProperties类的东西。

批注具有@Import(EnableConfigurationPropertiesImportSelector.class) 然后导入ImportBeanDefinitionRegistrar 这些注册商通过注释元数据传递:

public interface ImportBeanDefinitionRegistrar {

    public void registerBeanDefinitions(
            AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry);

}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM