Spring getBeanNamesForType运行不正常

时间:2016-09-13 08:04:20

标签: java spring

我有简单的上下文配置

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.ResolvableType;

import java.util.Arrays;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);

        String[] namesForType = ctx.getBeanNamesForType(ResolvableType.forClassWithGenerics(Transformer.class, Integer.class, String.class));

        System.out.println("namesForType = " + Arrays.toString(namesForType));
    }

    @Bean
    public Transformer<Integer, String> stringTransformer() {
        return new Transformer<Integer, String>();
    }
}

和简单的课程

package com.example;

public class Transformer<F, T> {

    T transform(F from) {
        return null;
    }
}

当我启动应用程序时,输出为 namesForType = []

如果将bean的创建更改为分离的类,如

    @Bean
    public Transformer<Integer, String> stringTransformer() {
        return new Transformer<Integer, String>(){};
    }

输出为 namesForType = [stringTransformer]

3 个答案:

答案 0 :(得分:0)

这是正确的行为。在使用@Bean注释之前,它不会在spring上下文中被选中。

答案 1 :(得分:0)

可能问题出在kode_matkul

org.springframework.core.ResolvableType#isInstance
obj.getClass()

public boolean isInstance(Object obj) {
    return (obj != null && isAssignableFrom(obj.getClass()));
}

因为public boolean isAssignableFrom(Class<?> other) { return isAssignableFrom(forClass(other), null); } 创建了可解析类型forClass(...)

但我无法理解

Transformer<?, ?>

可以注入正确的bean。

答案 2 :(得分:0)

Spring JIRA已经报道了问题。请投票支持这个问题。 https://jira.spring.io/browse/SPR-14118