Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What scopes exist in spring mvc?

I know in servlets many scopes(request, session....).

  1. How it correlates with Spring MVC?
  2. How can I use needful scope using Spring style?

I don't want directly use HttpRequest and HttpResponse.

like image 952
gstackoverflow Avatar asked Mar 16 '26 18:03

gstackoverflow


1 Answers

• Singleton: This scopes the bean definition to a single instance per Spring IoC container (default).

• Prototype: This scopes a single bean definition to have any number of object instances.

Message aMessage; //object

// singleton bean scope 
aMessageA = new Message();
aMessageA = (Message) applicationContext.getBean("message");
aMessageA.setText("message1 :D");
System.out.println(aMessageA.getText());

aMessageB = new Message();
aMessageB = (Message) applicationContext.getBean("message");
System.out.println(aMessageB.getText());
// result will be the same for both objects because it's just one instance.


// Prototype bean scope. scope="prototype"
aMessageA = new Message();
aMessageA = (Message) applicationContext.getBean("message");
aMessageA.setText("message :D");
System.out.println(aMessageA.getText());

aMessageB = new Message();
aMessageB = (Message) applicationContext.getBean("message");
System.out.println(aMessageB.getText());

/* first object will print the message, but the second one won't because it's a new instance.*/
like image 104
hasan.alkhatib Avatar answered Mar 18 '26 08:03

hasan.alkhatib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!