4

What are the differences between Lookup method injection, Provider<T>, ObjectFactory and factoryBean. If I want a new instance of a prototype (many times) into a singleton, which of them is the best solution? And if I want a new instance (many times) of a prototype bean into a prototype?

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
Alex
  • 2,075
  • 5
  • 27
  • 39

1 Answers1

1

please check my question too: How to instantiate spring managed beans at runtime?

As far as I understand the factoryBean is just a way to create bean with some complex instantiation logic. It is hard to define such logic in xml. It is well explained in spring documentation: http://springindepth.com/book/in-depth-ioc-factory-bean.html

Other three looks similar for me. But If you look at one spring issue https://jira.spring.io/browse/SPR-5192 you will find that javax.inject.Provider interface came from JSR-330 and I guess it was implemented in spring later than lookup method injection and looks like it is better solution. (The same thing is implemented in Google Guice DI)

Also with Object factory you have to write coupled with spring code(ObjectFactory requires spring import):

@Autowired
private ObjectFactory<PrototypeBean> beanFactory;
//...
beanFactory.getObject()

Upd Lookup, beanFactory and Provider doesn't support passing any parameters, i.e. you have Provider#get() but there is no Provider#get(Object... args)

Community
  • 1
  • 1
Vadim Kirilchuk
  • 3,532
  • 4
  • 32
  • 49
  • BeanFactory does support parameters: ` T getBean(Class requiredType, Object... args) throws BeansException;` – zyexal Oct 02 '22 at 09:23