Spring Component Scope (Request,session) example

Source: Internet
Author: User

Last said, the Spring component annotation scope has Singleton, prototype, request, session, global session such a few common scenarios . Here is a special note, according to the source code to show that the scope annotation is divided into configurablebeanfactory and webapplicationcontext two large classes, Configurablebeanfactory contains ( Singleton, prototype) there are two types of scope,webapplicationcontext below (Root_web_application_context_attribute,request, Session,application,servletcontext,contextparameters,contextattributes) so several scopes. Today's example focuses on testing request,session two scenarios at a time.

Before I talk about specific examples, I will share the experience of using these two scenarios in order to Grok with you crossing! We all know b/s site is running up, is a multi-threaded operating environment. Each client login will produce a session, its life cycle from the login system to the session expires, during which the information stored in the session is valid, I am accustomed to call it session-level cache, such as user login identity information we will generally bind to this session. Here we are going to talk about the @scope ("session"), which is a session-level bean scheme provided by spring, in which the Spring di function is used to get the component, so that there is only one instance of this component in the lifetime of the session. Then again, the request, the HTTP protocol processing model, from the client to initiate request requests, to the processing of the server, and finally response to the client, we call a complete request. During such a request, our service station may be called serial FUNCA->FUNCB->FUNCC ... Such a string of functions, if our system needs to do a careful check of permissions (user rights, data permissions), the more frightening is that the FUNCA,FUNCB,FUNCC is 3 people are implemented separately, but also to do a permission check. Then there's a good chance there will be 3 people each connected to the database, read the same batch of permissions data. Imagine that if a data read takes 2 seconds, then 3 methods will take 6 seconds of processing time. But in fact, this data is only used in the request process to read once, slow to exist in the request context, I am accustomed to call the thread-level cache. About thread-level caching Java has a threadlocal scenario in which a transaction like Hibernate is the only way to maintain a database connection during execution. Of course, today's @scope ("request") can also do this thread-level caching. Let's take a look at the specific test examples

To implement the test step description:

1. Create a bean component labeled @scope ("session"). About Proxymode This parameter, in order to resolve the dependent session or request context is not yet, the automatic loading component error, here to the JDK agent, can ensure that the environment is ready to execute the component load.

  @Component  //  @Scope (value=webapplicationcontext.scope_session)  @Scope (Value=webapplicationcontext.scope_session, Proxymode=scopedproxymode.interfaces)  public  class  sessionbean implements   Isessionbean { private     uuid uuid;  public   Sessionbean () {UUID  = Uuid.randomuuid ();  public  void   Printid () {System.out.println (" Sessionbean: "+uuid); }}

2. Create a @scope ("request") labeled Bean component

= webapplicationcontext.scope_request,proxymode= scopedproxymode.interfaces)Publicclass  implements  Irequestbean {    private  uuid uuid;      Public Requestbean () {        = uuid.randomuuid ();    }      Public void Printid () {        System.out.println ("Requestbean:" + uuid);}    }

3, add a multi-sample assembly of automatic assembly service class, easy to get session, request components.

@Service @scope (Value=configurablebeanfactory.scope_prototype)  Public class beaninstance {    @Autowired    private  Irequestbean Requestbean;    @Autowired    private  isessionbean Sessionbean;      Public Irequestbean Getrequestbean () {        return  requestbean;    }      Public Isessionbean Getsessionbean () {        return  sessionbean;    }}

4. Add test code

@Controller @requestmapping ("/USER")//Add the annotations of session information, can realize the map assignment of session information and map@SessionAttributes ("User") Public classUsercontroller {@AutowiredPrivatebeaninstance BeanInstance1; @AutowiredPrivatebeaninstance BeanInstance2; @RequestMapping (Value= "/login", method =requestmethod.get) Publicstring Login (string name, model model, HttpServletRequest request, HttpSession session) {Model.addattribute ( /c1>"User", name);System.out.println ("SessionBean-1");        Beaninstance1.getsessionbean (). Printid (); System.out.println ("SessionBean-2");        Beaninstance1.getsessionbean (). Printid (); System.out.println ("RequestBean-1");        Beaninstance2.getrequestbean (). Printid (); System.out.println ("RequestBean-2");        Beaninstance2.getrequestbean (). Printid (); return"User/check"; }    /*** Check the automatic loading information *@parammodel *@paramRequest *@paramSession *@return     */@RequestMapping (Value= "/check", method =requestmethod.get) PublicString Check (model, HttpServletRequest request, HttpSession session) {System.out.println ("SessionBean-1");        Beaninstance1.getsessionbean (). Printid (); System.out.println ("SessionBean-2");        Beaninstance1.getsessionbean (). Printid (); System.out.println ("RequestBean-1");        Beaninstance2.getrequestbean (). Printid (); System.out.println ("RequestBean-2");        Beaninstance2.getrequestbean (). Printid (); return"User/check"; }}

5, start a login request, and then initiate a check request after login. From the printed test results can see two requests to get the session component, the corresponding ID is the same, so in the same session, the sessions component is unique. The request component, in the same request process, invokes both the same component ID and the ID of the request component in the second request. So as mentioned above, the @Scope ("request") pattern is the only component that spring returns during the same request, and we can use this scheme to do thread-level data caching.

Resources

Https://www.cnblogs.com/waytofall/p/3460533.html
Https://www.cnblogs.com/lonecloud/p/5937513.html

Spring Component Scope (Request,session) example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.