我和你做过同样的事情。好的方法是使用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 { ... }
其次,定义并添加一个实现BeanPostProcessor和ApplicationContextAware的 bean到您的应用程序上下文中。
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;
}
}
希望它会有所帮助。