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

标签 spring configuration annotations

我有这个 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/

相关文章:

java - CascadeType.Persist 没有按预期工作

java - 从 Java 7 更改 RequestMapping 方法或在 Java 8 中添加 Optional

java - 无法导入 org.thymeleaf.templatemode.TemplateMode

java - Spring 启动组件扫描问题

java - 如何通过config.properties从pom.xml获取参数值

eclipse - Ubuntu 19.04 上 Eclipse 4.11 中的巨大选项卡和图标填充

Spring 集成 RecipientListRouter 不会创建多个有效负载

wcf - 如何配置自定义安全 token 处理程序?

java - 我们应该@Override 接口(interface)的方法实现吗?

java - Spring使用运行时对象设置属性?