The scope of the bean in spring

Source: Internet
Author: User

The beans in the spring container have different scopes, starting with Singleton and prototype, but after 2.0, three more types are introduced: request, session, and global session, However, these three types can only be used in web apps.

When you define a bean, you can specify the scope of the corresponding object by specifying the singleton or scope property of <bean>, for example:

<bean id="testMock" class="org.test.javadu.TestMock" scope="prototype"/>


<bean id="testMock" class="org.test.javadu.TestMock" singleton="false"/>
1. Singleton

A bean definition in a configuration can be thought of as a template, and the container constructs the object based on the template. The scope semantics in the bean definition determine how many object instances the container will construct based on the template, and how long the object instance should be allowed to survive. Marked as an object definition with singleton scope, there is only one instance of an object in the spring IOC container, and all references to that object share this instance. The instance is started and, after being initialized for the first time, it will survive until the container exits, that is, it "almost" has the same "lifespan" as the IOC container.

is the instantiation and injection semantics of the singleton bean given in the spring reference document, and perhaps more visually illustrates the problem.

Singleton scope

It is important to note that the concept of the Singleton bean in spring is not confused with the singleton pattern proposed in the GOF, and the semantics are not the same: the singleton scope in spring refers to an instance object with only one bean in each container ; Singleton in Gof mode refers to an instance object that has only one singleton class in the same ClassLoader.

The beans in spring are singleton by default, and the following two ways are the same:

<bean id="accountService" class=""/><!-- the following is equivalent, though redundant (singleton scope is the default) --><bean id="accountService" class="" scope="singleton"/>
2. Prototype

For a bean definition declared to have prototype scope, the container regenerates a new instance object to the requester each time it receives a request for that type of object. Although the instantiation of this type of object and the property setting are all handled by the container, the container will no longer have a reference to the currently returned object, as long as it is ready, and after the object instance returns to the requester, the requester needs to be responsible for the management of the subsequent declaration cycle of the currently returned object, such as the object's destruction. That is, each time a container returns to a new instance object from the requester, the object "dies".

For those object types that the requester cannot share, the scope of its bean definition should be set to prototype. In this way, each requester can get its own proprietary instance of an object. Typically, objects declared as prototype are stateful, such as the object that holds each customer's information.

From this image under the Spring Reference document, you can learn again about the bean definition of prototype scope, and what its specific semantics will be when instantiating objects and injecting dependencies.

Prototype scope

The effect is the same as defined by the following two ban:

<bean id="accountService" class="" scope="prototype"/><bean id="accountService" class="" singleton="false"/>
Practical Lessons

The reason for writing this topic today is that, in recent projects, the statistics on the daily scheduled tasks have been faulted due to the lack of understanding of the objects of the singleton type.

It is described as follows: Every day I need to run a timed task, the task is executed in a multi-threaded way, each thread needs to write data to a unified result set, the basic code structure is as follows:

PublicClassStatisticstaskmanager {PrivateStaticFinal Logger Logger = Loggerfactory.getlogger (Odsmanager.class);Private Concurrenthashmap<long, statisticsbean> Resultmap =New Concurrenthashmap<> ();/* External Exposure Statistics interface */Public list<statisticsbean>Getodsstatisticdatafromutc() {Executorservice pool = Executors.newfixedthreadpool (80);for (int dbindex = 0; dbindex < constants.db_num; dbIndex++) {for (int tableindex = 0; TableIndex < Constants.table_num; tableindex++) {dealuidrunnable thread = new dealuidrunnable (Dbindex, TableIndex); Pool.execute (thread); }} pool.shutdown (); try {pool.awaittermination (6, timeunit.hours);} catch (interruptedexception e) {logger.error (" error: ", e);} ( "finished! num={} ", Resultmap.size ()); //resultmap.clear (); return convertmaptolist ();} /* specific task Execution Process * * This will modify Resultmap}          

In the code snippet above, each thread will determine if a key exists in Resultmap, update the corresponding bean if it exists, and create a new bean if it does not exist. This requires that the Resultmap be empty before each task starts executing, but I do not realize that the Resultmap is only initialized once with the Statisticstaskmanager object's generation, and subsequent objects are present in the container as the singleton object.

The modification is also very simple, that is, after the day's scheduled tasks are executed, the call resultMap.clear() will clear the data in the result map.

    1. "Secret Spring"
    2. Spring Official documentation

Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

The scope of the bean in spring

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: 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.