|
|||||
|
|||||
To Singleton or Not To Singleton
Default SettingBy default, components defined in the global scope are singleton, unless explicitly specified otherwise. This default global setting can be changed by changing the "singleton" attribute on the <module> tag. Components defined within a local scope (inside <local>, <sequence>, <binder> or any other tags) are not singleton by default. This default behavior can only be changed on each individual component definition using the "singleton" attribute. For example: ... <local> <ctor id="acct" class="BankAccount" singleton="true"/> </local> ...
Mix singleton and non-singletonSometimes, we may want to have a bean such that, the instance itself is singleton in the sense that the same instance is returned every time it is instantiated; one or more properties are not singleton, in the sense that different property values are set every time this component is instantiated. Writing it in Java, it will look like: private BankAccount singleton; private BankAccount getSingletonInstance(){ if(singleton==null){ this.singleton = new BankAccount(); } return singleton; } public synchronized BankAccoun getInstance(){ final BankAccount instance = getSingletonInstance(); instance.setJoint(new BankAccount()); }
Every time getInstance() is invoked, the same instance is returned, but a different BankAccount object is created for the "joint" property. The Spring framework has a solution for it, but pretty heavy and requires bytecode generation. This is the Spring note for this issue:
In Nuts, this is no harder than a "singleton uses singleton", "non-singleton uses non-singleton" or "non-singleton uses singleton" senario. Nuts handles quite complex component combinations. The "singleton uses non-singleton" case is among the easiest ones. All we have to do is to create the singleton base component and the non-singleton bean component that injects the non-singleton properties to the singleton base: <bean id="acct" singleton="false" synchronized="true"> <bean class="BankAccount" args="" singleton="true"/> <prop key="joint"> <ctor class="BankAccount"/> </prop> </bean> The "synchronized" attribute is used to indicate that a "synchronized" block should enclose the instantiation process. Created by benyu |
|||||
|
Copyright 2003-2006 - The Codehaus. All rights reserved unless otherwise noted.
Powered by Atlassian Confluence
|
|||||