![](/img/trans.png)
[英]Is there any way to enable/disable a annotation by property in 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.