Results 1 to 4 of 4

Thread: Factory method in spring (newb question)

  1. #1
    Join Date
    Nov 2011
    Posts
    5

    Default Factory method in spring (newb question)

    Hello,

    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
    noirc

  2. #2
    Join Date
    Jul 2010
    Location
    Venice, Italy
    Posts
    709

    Default

    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. #3
    Join Date
    Nov 2011
    Posts
    5

    Default

    well, i wanna do this instantiating at runtime

  4. #4
    Join Date
    Jul 2010
    Location
    Venice, Italy
    Posts
    709

    Default

    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).

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •