http://blog.csdn.net/anyoneking/article/details/5182164
In spring's bean configuration, there are two scenarios:
[XHTML]View Plaincopy
- <Bean id="Testmanager" class="Com.sw.TestManagerImpl" scope= "singleton"/>
- <Bean id="Testmanager" class="Com.sw.TestManagerImpl" scope= "prototype " />
Of course, the scope has more than two values, including Request,session, and so on. But the most used is the singleton single State, prototype polymorphic.
Singleton indicates that there is only one instance of the bean globally, and the bean's scope in spring is singleton by default.
Prototype indicates that the bean will recreate an instance each time it is injected, which applies to stateful beans.
For the SSH architecture system, there is little interest in this aspect, because we use singleton generally. Bean injection is managed by spring.
What about a stateful bean?
The following is a stateful bean
[Java]View Plaincopy
- Package COM.SW;
- Public class Testmanagerimpl implements testmanager{
- Private User User;
- public void DeleteUser (User e) throws Exception {
- user = e; //1
- Preparedata (e);
- }
- public void Preparedata (User e) throws Exception {
- user = Getuserbyid (E.getid ()); //2
- .....
- //Use User.getid (); 3
- .....
- .....
- }
- }
What happens if the bean is configured as singleton?
If there are 2 user accesses, it is called to the bean.
assumed to be User1,user2
When User1 calls to 1 steps in the program, the bean's private variable user is paid the value of User1
When the User1 program goes to 2 steps, the bean's private variable user is re-paid the value of User1_create
Ideally, when User1 goes to 3 steps, the private variable user should be user1_create;
If, however, the user2 starts to run to 1 steps before User1 calls to 3, the private variable user is modified to User2 because of a single-state resource share.
In this case, the User.getid () used in step 3 of User1 is actually used to be the object of User2.
And if it is prototype, there will be no problem of resource sharing.
For SSH, the bean configuration is correct, configured as singleton; the actual should be this example should not use private variables. This makes the bean
Changed from stateless to stateful bean. You should try to use a stateless bean as much as possible. If a private variable appears in the program, try to replace it with a parameter.
For each method that accesses a private variable, it is a good idea to add a variable or get it through threadlocal.
Really appear above the code problem is also a few, when it occurs, is generally convenient for the diagram, a lot of ways to use the variable, if you need to use parameters of the
How troublesome it is to pass the way, so the private variables are so good that they are not as ugly as the parameters. But ugliness does not mean bad, to the right, their habits of the way programming, to
Try to avoid problems.
Spring Bean has a state bean without state bean