我有从配置值创建相同类的实例,因此我需要从该配置值注入/自动装配它们。我在guice
中这样做:
for (String s : config.getStrings()) {
bind(Foo.class).annotatedWith(Names.named(s)).toInstance(new Foo(s));
}
有没有办法在Spring
中执行此类操作,或者是否有办法使用类似FactoryBean
的内容创建给定qualifier
的类的实例?
答案 0 :(得分:2)
public final class FLEXSyncFactory implements ApplicationContextAware {
private static AbstractApplicationContext context;
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
context = (AbstractApplicationContext) applicationContext;
}
注册bean的别名
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();
Foo fooBean = beanFactory.getBean(Foo.class);
beanFactory.initializeBean(fooBean, "TheAliasForBeanNameYouNeed");
beanFactory.autowireBeanProperties(fooBean, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);