请教关于泛型自动装配的问题,@Autowired失败,s1和s2都是null,报错说循依赖(Circular reference )
老师
你好,我按照你的代码测试StoreConfig类,但是无法Autowired s1和s2,报错信息如下:
我的Spring版本是4.1.4。请帮忙看一下,谢谢。
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.springtest.beanannotation.store.Store com.springtest.beanannotation.store.StoreConfig.s1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stringStoreTest' defined in com.springtest.beanannotation.store.StoreConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.springtest.beanannotation.store.Store]: Circular reference involving containing bean 'storeConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'stringStoreTest' threw exception; nested exception is java.lang.NullPointerException
各个类的代码如下:
//Interface Store<T> package com.springtest.beanannotation.store; public interface Store<T> { } //IntegerStore package com.springtest.beanannotation.store; public class IntegerStore implements Store<Integer> { } //StringStore package com.springtest.beanannotation.store; public class StringStore implements Store<String> { public void init(){ System.out.println("This is Init."); } public void destroy(){ System.out.println("This is Destroy."); } } //StoreConfig @Configuration @ImportResource("classpath:config.xml") public class StoreConfig { @Autowired private Store<String> s1; @Autowired private Store<Integer> s2; @Bean public StringStore stringStore(){ return new StringStore(); } @Bean public IntegerStore integerStore(){ return new IntegerStore(); } @Bean(name="stringStoreTest") public Store stringStoreTest(){ System.out.println("s1:"+s1.getClass().getName()); System.out.println("s2:"+s2.getClass().getName()); return new StringStore(); } } //TestStore public class TestStore extends UnitTestBase { public TestStore(){ super("classpath*:spring-beanannotation.xml"); } @Test public void testG(){ StringStore store = super.getBean("stringStoreTest"); } } //配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" > <context:component-scan base-package="com.springtest.beanannotation"></context:component-scan> </beans>