Announcement Announcement Module
No announcement yet.
Factory method in spring (newb question) Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Factory method in spring (newb question)


    Is it possible to define a kind of factory-method in Spring. I have an interface MyService and two implementation FooService and BarService. In one case i wanna link to FooService in another to BarService.

    tia && regards

  • #2
    Not sure I fully understand your question, however let me point out that the "Factory Pattern" is automatically implemented by Spring's application context (in fact it is even more than that since Spring uses singletons by default). All you need to do is program by interfaces and wire your specific implementations using dependency injection.


    • #3
      well, i wanna do this instantiating at runtime


      • #4
        with Spring's default scope for beans which is singleton, there is no instantiation at runtime. 1 copy of each bean is instantiated only once, when the application context is loaded. Then, for the entire lifecycle of that application context, that single instance is used. Things change if you use a scope different than singleton, if you use lazy loading, if you refresh the application context.

        If by "I want to instantiate at runtime" you mean you want to decide which collaborators (specific implementation) to inject in a certain bean at runtime, based on some condition, I'm afraid this goes against Spring dependency injection principle. You could achieve that by refreshing the application context (which is time and resource consuming) or by hacking into the framework itself (not recommended).