MapFactoryBean
可以通过此FactoryBean动态的设定某个接口或者类的自动注入后在被Controller使用时具体使用的是哪个实现类。但是在Controller中注入时需要使用@Resource注解注入,因为如果出现了多个MapFactoryBean的配置将会无法注入,即使使用了@Qulifier指定了id也不行;且注入的类需要写成Map类而不是MapFactoryBean
//WebMvcConfigurerAdapter的实现类配置MapFactoryBean如下
@Bean(name="testFamilyMapFactoryBean")
public MapFactoryBean mapFactoryBean2(){
MapFactoryBean fmb = new MapFactoryBean();
fmb.setTargetMapClass(HashMap.class);
Map<String,TestFamily> map = new HashMap<>();
map.put("testFamily",testFamily());
fmb.setSourceMap(map);
return fmb;
}
@Bean(name="familyMapFactoryBean")
public MapFactoryBean mapFactoryBean(){
MapFactoryBean fmb = new MapFactoryBean();
fmb.setTargetMapClass(HashMap.class);
Map<String,IFamilyService> map = new HashMap<>();
map.put("familyService",familyService);
map.put("chinaFamilyService",chinaFamilyService);
map.put("americanFamilyService",americanFamilyService);
fmb.setSourceMap(map);
return fmb;
}
//Controller中的配置
@Resource(name = "familyMapFactoryBean")
/*@Autowired
@Qualifier("familyMapFactoryBean")*/
private Map<String,IFamilyService> mapFactoryBean;
@Resource(name="testFamilyMapFactoryBean")
/*@Autowired
@Qualifier("testFamilyMapFactoryBean")*/
private Map<String,TestFamily> mapFactoryBean2;