gpt4 book ai didi

spring - 如何使用自定义注释 @Foo 找到所有 bean?

转载 作者:IT老高 更新时间:2023-10-28 13:45:47 36 4
gpt4 key购买 nike

我有这个 Spring 配置:

@Lazy
@Configuration
public class MyAppConfig {
@Foo @Bean
public IFooService service1() { return new SpecialFooServiceImpl(); }
}

如何获得所有带有 @Foo 注释的 bean 的列表?

注意:@Foo是我定义的自定义注解。它不是“官方”的 Spring 注释之一。

[编辑]按照 Avinash 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:<[[]]> .为什么?

最佳答案

使用 getBeansWithAnnotation()获取带有注解的bean的方法。

Map<String,Object> beans = applicationContext.getBeansWithAnnotation(Foo.class);

Here是类似的讨论。

关于spring - 如何使用自定义注释 @Foo 找到所有 bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14236424/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com