私の質問は、java.util.Map
のタイプのBeanを@Autowired
経由でクラスに挿入する方法に関するものです。具体的には、クラス内のAutowired Beanの値は、実際にはキーが1つのキーと値のペアを含むMapであり、そのキーはBeanの名前であり、その値は注入することを意図している。私は春が地図を直接注入したと思った。ここでマップ動作の春のオートワイヤリング
は、私は豆をautowireするクラスです。
@Component
public class SpringMapParent {
@Autowired
@Qualifier("theMap")
private Map<String, Object> theMap;
...
}
私はこのように私の春のJava構成でtheMap
定義:マップのサイズが0
@Configuration
@ComponentScan
public class SpringMapConfiguration {
@Bean("theMap")
public Map<String, Object> getTheMap() {
Map<String, Object> theMap = new HashMap<String, Object>();
return theMap;
}
...
}
注意
この注入をテストする私のユニットテストは失敗します:
@ContextConfiguration(classes = {SpringMapConfiguration.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringMapIT {
@Autowired
private SpringMapParent springMapParent;
@Test
public void testSpringMapParentAutowiredCorrectly() {
Map<String, Object> theMap = springMapParent.getTheMap();
assertEquals(0, theMap.size());
}
}
theMap
の大きさは、実際には1つのエントリがあるさ:
{theMap={}}
これはなぜでしょうか?そして、実際にbean内で定義されたマップをtheMap
フィールドに直接挿入するにはどうすればよいですか?