• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

Few questions on Spring

 
Ranch Hand
Posts: 212
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1) I know that in singleton scope everytime I do a context.getBean("..") it would return the same object and in prototype scope the same would retrieve  new object everytime. Can someone give an example when it would make sense to go for singleton and when to go for prototype?

2) Is dependency injection related to coding to interfaces? Or they are different concepts which can be used together?
 
Sheriff
Posts: 9697
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1) Generally if your bean stores some state i.e. has some instance variables which you set when using the bean, then it makes sense to make it prototype. If the bean is stateless as far as the client is concerned, then make it singleton. So in following case you should ideally make it prototype:

In the above example, I'm changing the state of the bean which I would expect not to change when the process method is called. If I make this bean singleton, then if multiple threads work on the same bean, I'll have unexpected results as the params set on the bean would change before I call the process method.

2) Coding to interfaces is a separate concept which works very well with dependency injection as well. But even without dependency injection, you should use coding to interface. A simple example is instead of writing ArrayList<String> strList = new ArrayList<>();, you change the type of strList from ArrayList to List as: List<String> strList = new ArrayList<>();...
 
reply
    Bookmark Topic Watch Topic
  • New Topic