0

I'm using Spring 3.1.1 and in my business logic, I have a loop which requires a new instance of a spring bean (prototype scope) for each iteration.

What is the best method to do this? Must I create my own BeanFactory class which I can inject once into my class, and call upon it every time to produce the bean upon request? When looking at the Spring 3 docs, it seems to imply that I should use ApplicationContext instead. However, using ApplicationContext makes my code Spring dependent.

What is the best method for something like this? Does Spring already provide a factory of sorts that I can leverage?

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
Eric B.
  • 23,425
  • 50
  • 169
  • 316

3 Answers3

1

ApplicationContext is the factory. You don't have to inject it into your class; you instantiate one and use it to create the beans and wire up their dependencies.

I don't understand the comment "using ApplicationContext makes my code Spring dependent." Yes, it does. Do you think DI is worth it or not?

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • Absolutely DI is worth it. But Spring is not the only DI container that exists. – Eric B. Nov 24 '12 at 01:35
  • No one said it was. The question was specifically about Spring. – duffymo Nov 24 '12 at 03:31
  • Touché. It my mind, it was clear that I was looking for a container independent solution, but I never made that clear in the question. Tx. – Eric B. Nov 26 '12 at 16:56
  • I don't think a container independent solution is possible, unless you go to great lengths to wrap everything and hide the fact that it's Spring or Guice from yourself. Personally, I wouldn't see the point. – duffymo Nov 26 '12 at 17:41
0

I think you should go with spring. Spring facilitates your need. You can use a method to lookup bean of specific type from application context. So if you make that bean to be prototype. then when you call this special method, you will be returned with a new instance of the bean you want.

You will find it indetails here!

Sazzadur Rahaman
  • 6,938
  • 1
  • 30
  • 52
  • When you find yourself posting an "answer" that starts with "I think you should go with", *post a comment* – drew moore Jul 22 '14 at 10:30
  • I think you missed the key point of the question somehow, because the question was asking for a suggestion! So there are nothing that is absolutely right or usable. Depending on contexts and usefulness we have to choose an approach! That is why the answer was started like that! And thanks for your suggestion! – Sazzadur Rahaman Jul 24 '14 at 04:10
0

You can use custom scope and make the injecting bean proxy, and on the custom scope bean listen to some dynamic events that can inject the underling proxy bean

Kalyan
  • 1