[英]How to get annotation metadata of spring beans
在我的 spring 項目中,我有多個接口實現。
interface Car {
}
@Component
@ColorOptions({Color.RED})
class SportsCar implements Car {
}
class Truck implements Car {
}
@Configuration
class CarConfiguration {
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@ColorOptions({Color.GREEN, Color.BLUE})
public Truck oldTruck() {
return new Truck();
}
@Bean
@ColorOptions({Color.BLUE})
public Truck newTruck() {
return new Truck();
}
}
我想要實現的是創建一個 spring bean,它是一個Map
包含接口的所有實現,這些實現將根據ColorOptions
注釋中提供的元數據進行分組。
@Bean
public Map<Color, List<Car>> groupedCars(List<Car> cars) {
// ???
return null;
}
org.springframework.beans.factory.ListableBeanFactory#findAnnotationOnBean
提供了一個選項來做到這一點,但我只能在我注釋一個類的情況下才能接收值。 對於在方法中定義的 spring bean,我什么也得不到。 另外我想避免注入整個ApplicationContext
並只注入接口的實現。 我該如何實施?
您可以使用 java 反射來遍歷這些方法
public class RunCarConfiguration {
public static void main(String[] args) throws Exception {
System.out.println("Testing grouped car ...");
Class<CarConfiguration> obj = CarConfiguration.class;
// Process @ColorOption
if (obj.isAnnotationPresent(ColorOptions.class)) {
Annotation annotation = obj.getAnnotation(ColorOptions.class);
ColorOptions colorOptions = (ColorOptions) annotation;
System.out.printf("%nColor :%s", colorOptions.color());
System.out.printf("%nLastModified :%s%n%n",
colorOptions.lastModified());
}
Map <ColorOptions.Color, Car> groupedCar = new HashMap<ColorOptions.Color, Car>();
// Process @Test
for (Method method : obj.getDeclaredMethods()) {
// if method is annotated with @Test
if (method.isAnnotationPresent(ColorOptions.class)) {
Annotation annotation = obj.getAnnotation(ColorOptions.class);
ColorOptions colorOptions = (ColorOptions) annotation;
try {
method.invoke(obj.newInstance());
if (method.isAnnotationPresent(ColorOptions.class)) {
System.out.printf("Test '%s' - has method annnotation %s %n" ,
method.getReturnType().getName(),
method.getAnnotation(ColorOptions.class).color());
groupedCar.put( method.getAnnotation(ColorOptions.class).color(),
(Car)method.invoke(obj.newInstance()));
}
} catch (Throwable ex) {
System.out.printf("Test '%s' - failed: %s %n" ,
method.getName(), ex.getCause());
}
}
}
}
}
您是否嘗試過 ComponentScan
@Configuration
@ComponentScan(includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION,
classes = ColorOption.class))
public class ComponentScanAnnotationFilterApp { }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.