spring注入模板化类对象

bxfogqkk  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(419)
@Component
public class A<K, V> {
    @Autowired
    // spring unable to inject this, @Qualifier can not use here
    private B<K, V> b; 
}

public class B<K, V>{}

@Configuration
public class ConifgA {
    @Bean
    @Qualifier("int_a")
    public A<Integer, Integer> getA1() { return new A<>(); }

    @Bean
    @Qualifier("int_a")
    public A<String, String> getA2() { return new A<>(); }
}
@Configuration
public class ConifgB {
    @Bean
    public B<Integer, Integer> getB1() { return new B<>(); }

    @Bean
    public B<String, String> getB2() { return new B<>(); }
}
@Component
class C {
    @Autowired
    @Qualifier("int_a")
    A<Integer, Integer> ia;

    @Autowired
    @Qualifier("str_a")
    A<String, String> sa;
}

我无法手动新建b()并将其传递给a的ctor,因为b包含spring注入的数据成员

f1tvaqid

f1tvaqid1#

@Qualifier 通常与 @Autowired 当上下文中有多个具有共享接口的bean示例时,按名称指定单个bean候选者。如果希望注入所需的bean名称,只需在 @Bean 作品。
我编写了一个适用于您的场景的测试类:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = FooTest.TestConfig.class)
public class FooTest {

    @Autowired
    private C c;

    @Test
    public void testCisAvailable(){
        Assert.assertNotNull(c);
    }

    @Configuration
    static class TestConfig {

        @Bean("int_a")
        public A<Integer, Integer> getA1(B<Integer, Integer> b) {
            return new A<>(b);
        }

        @Bean("str_a")
        public A<String, String> getA2(B<String, String> b) {
            return new A<>(b);
        }

        @Bean
        public B<Integer, Integer> getB1() {
            return new B<>();
        }

        @Bean
        public B<String, String> getB2() {
            return new B<>();
        }

        @Bean
        public C getC(A<Integer, Integer> ia,
                      A<String, String> sa) {
            return new C(ia, sa);
        }
    }

    static class B<K, V> {
    }

    static class A<K, V> {

        private final B<K, V> b;

        @Autowired
        public A(B<K, V> b) {
            this.b = b;
        }
    }

    static class C {

        private final A<Integer, Integer> ia;
        private final A<String, String> sa;

        @Autowired
        public C(@Qualifier("int_a") A<Integer, Integer> ia,
                 @Qualifier("str_a") A<String, String> sa) {
            this.ia = ia;
            this.sa = sa;
        }

    }

}

相关问题