Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从ApplicationContext获取泛化类?_Java_Spring_Autowired - Fatal编程技术网

Java 如何从ApplicationContext获取泛化类?

Java 如何从ApplicationContext获取泛化类?,java,spring,autowired,Java,Spring,Autowired,你能帮我澄清一下在春天我该如何处理泛型吗 在下面的示例中,异常NoniqueBeandDefinitionException:没有抛出类型为'java.lang.Object'的合格bean可用 public class Launcher { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(AppCon

你能帮我澄清一下在春天我该如何处理泛型吗

在下面的示例中,异常
NoniqueBeandDefinitionException:没有抛出类型为'java.lang.Object'的合格bean可用

public class Launcher {

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        FooService<String> fooService = context.getBean(FooService.class);
        fooService.printVal();
    }

}

你能告诉我强制代码段正常工作的最佳方法是什么吗?< /P> < P>自Spring 4起,它会自动将泛型视为@限定符的形式,如下:

@Autowired
private Item<String> strItem; // Injects the stringItem bean

@Autowired
private Item<Integer> intItem; // Injects the integerItem bean
@Autowired
私人物品横档;//注入StringItembean
@自动连线
私有项初始项;//注入integerItem bean

因此,您应该在构造函数方法中指明名称(在本例中为“string”)。

您首先不会将这样的泛型类定义用作服务。当你把它变成一个
@Service
或bean时,通常它必须是一个指定类型的成品<代码>上下文。getBean不是一个根据您的规范生成对象的工厂,它只提供上下文中存在的对象。你的应用程序崩溃是因为甚至在你“请求”
FooService
(如果没有强制转换就不能工作)之前,它就崩溃了,因为它无法将
对象
自动关联到
FooService
构造函数中,因为没有
V
的定义,因此它是
对象
@Configuration
@ComponentScan("service")
public class AppConfig {

    @Bean
    public String string() {
        return "simple string";
    }

}
@Autowired
private Item<String> strItem; // Injects the stringItem bean

@Autowired
private Item<Integer> intItem; // Injects the integerItem bean