• Post Reply Bookmark Topic Watch Topic
  • New Topic

Few questions on Spring  RSS feed

 
raja singh kumar
Ranch Hand
Posts: 179
1
  • Mark post as helpful
  • send pies
  • 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?
 
Ankit Garg
Sheriff
Posts: 9609
36
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • 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<>();...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!