假设我有一组bean(a,b,c)实现了一个接口和一个地图。
M.xml
<bean name="map" class="java.util.HashMap"/>
abc.xml
<import M.xml>
<bean name="a" class="org.a"/>
<bean name="b" class="org.b"/>
<bean name="c" class="org.c"/>
def.xml
<import M.xml>
<bean name="d" class="org.d"/>
<bean name="e" class="org.e"/>
<bean name="f" class="org.f"/>
我希望在实例化配置后将a,b,c放入地图中。当然a,b,c不应该知道地图。此注册应使用导入包含在配置中,因为在另一种情况下,它可能是d,e,f,必须进行注册。我应该使用哪种Spring扩展机制?
由于
答案 0 :(得分:1)
您可以使用@Autowired
。如果使用它标记集合,它将把匹配接口的所有bean放在此集合中。您的“map”bean应该是MyMap
下面的类型:
public class MyMap implements Map {
@Autowired
private List<SharedInterface> foundBeans;
@PostConstruct
public void init() {
// populate map by inserting objects from foundBeans with appropriate keys
}
}
或者,使用原始的“map”bean并添加此类的mapBuilder bean:
public class MyMapBuilder {
@Autowired
private List<SharedInterface> foundBeans;
@Resource(name="map")
private Map map;
@PostConstruct
public void init() {
// populate map by inserting objects from foundBeans with appropriate keys
}
}
答案 1 :(得分:1)
我和你做过同样的事情。好方法是使用 BeanPostProcessor 和 ApplicationContextAware 。
首先,让a,b,c实现标记接口,例如:
public interface MappedValue { //leaving blank is ok because this is marker interface }
public a implements MappedValue { ... }
public b implements MappedValue { ... }
public c implements MappedValue { ... }
其次,定义并添加一个bean,它将 BeanPostProcessor 和 ApplicationContextAware 实现到您的应用程序上下文中。
public class MapPopulator implements BeanPostProcessor, ApplicationContextAware{
private ApplicationContext applicationContext;
private String mapbeanName;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void setMapbeanName(String mapbeanName) {
this.mapbeanName = mapbeanName;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if( bean instanceof MappedValue){
Map map = (Map)applicationContext.getBean( mapbeanName );
map.put( beanName, bean );
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
希望它会有所帮助。