我有這個春天的配置:如何使用自定義註釋@Foo查找所有bean?
@Lazy
@Configuration
public class MyAppConfig {
@Foo @Bean
public IFooService service1() { return new SpecialFooServiceImpl(); }
}
我怎樣才能被標註有@Foo
所有Bean的列表?
注:@Foo
是由我定義的自定義註釋。這不是「官方」的Spring註釋之一。
[編輯]繼阿維納什T的建議,我寫了這個測試案例:
import static org.junit.Assert.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.reflect.Method;
import java.util.Map;
import org.junit.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
public class CustomAnnotationsTest {
@Test
public void testFindByAnnotation() throws Exception {
AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(CustomAnnotationsSpringCfg.class);
Method m = CustomAnnotationsSpringCfg.class.getMethod("a");
assertNotNull(m);
assertNotNull(m.getAnnotation(Foo.class));
BeanDefinition bdf = appContext.getBeanFactory().getBeanDefinition("a");
// Is there a way to list all annotations of bdf?
Map<String, Object> beans = appContext.getBeansWithAnnotation(Foo.class);
assertEquals("[a]", beans.keySet().toString());
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public static @interface Foo {
}
public static class Named {
private final String name;
public Named(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
@Lazy
@Configuration
public static class CustomAnnotationsSpringCfg {
@Foo @Bean public Named a() { return new Named("a"); }
@Bean public Named b() { return new Named("b"); }
}
}
,但它失敗org.junit.ComparisonFailure: expected:<[[a]]> but was:<[[]]>
。爲什麼?
謝謝,我完全錯過了。我寫了一個測試用例,但測試失敗(請參閱我編輯的問題)。任何想法爲什麼? –
@AaronDigulla .....你的assertEquals()拋出這個異常。 –
這是因爲'getBeansWithAnnotation()'返回一個空映射 - >它沒有找到任何bean。這是爲什麼? –