使用 FactoryBean 进行动态 bean 实例化
为了动态决定注入哪些 bean,我们可以使用 FactoryBean
s。这些是实现工厂方法模式的类,为容器提供 bean 实例。它们被 Spring 识别并且可以透明地使用,而不需要知道 bean 来自工厂。例如:
public class ExampleFactoryBean extends AbstractFactoryBean<String> {
// This method determines the type of the bean for autowiring purposes
@Override
public Class<?> getObjectType() {
return String.class;
}
// this factory method produces the actual bean
@Override
protected String createInstance() throws Exception {
// The thing you return can be defined dynamically,
// that is read from a file, database, network or just
// simply randomly generated if you wish.
return "Something from factory";
}
}
组态:
@Configuration
public class ExampleConfig {
@Bean
public FactoryBean<String> fromFactory() {
return new ExampleFactoryBean();
}
}
得到豆子:
AbstractApplicationContext context = new AnnotationConfigApplicationContext(ExampleConfig.class);
String exampleString = (String) context.getBean("fromFactory");
要获取实际的 FactoryBean,请在 bean 的名称前使用&符号前缀:
FactoryBean<String> bean = (FactoryBean<String>) context.getBean("&fromFactory");
请注意,你只能使用 prototype
或 singleton
范围 - 将范围更改为 prototype
override isSingleton
方法:
public class ExampleFactoryBean extends AbstractFactoryBean<String> {
@Override
public boolean isSingleton() {
return false;
}
// other methods omitted for readability reasons
}
请注意,作用域指的是创建的实际实例,而不是工厂 bean 本身。