• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

any DI example for local variable?

 
peter tong
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just start to learn spring and I see many tutorial just talking about DI for class member variable
e.g. http://www.tutorialspoint.com/spring/setter_based_dependency_injection.htm
, but how to do DI for local variable (inside method)? any example?
 
Bill Gorder
Bartender
Posts: 1682
7
Android IntelliJ IDE Linux Mac OS X Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't do this and why would you want to? Can you give me a use case where you would need to do this?
 
peter tong
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bill Gorder wrote:You don't do this and why would you want to? Can you give me a use case where you would need to do this?


No special reason, just see all example about DI is for member variable, maybe I do not understand why need to use DI and so ask this question. At first, I think in spring application, there should be no any NEW Class statement. this is wrong concept?
 
Bill Gorder
Bartender
Posts: 1682
7
Android IntelliJ IDE Linux Mac OS X Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Spring only does DI in Spring managed beans. Typically these are Services or Repositories which usually make sense as singletons (only one bean with that name existing in a given application context). Not every object is a good candidate to be Spring managed. Local variables even in these beans are still created with the new operator. You usually (this is possible but I would not worry about that for now) do not create Spring managed beans with the new operator. You define your beans and Spring creates the objects and manages the bean lifecycles and dependencies. This explanation is a bit oversimplified but if you have more specific questions let me know.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic