Spring singleton class instances created? - java

I have the following spring configuration.
<bean id="abcService1" class="com.service.ABCServiceImpl" />
<bean id="abcService2" class="com.service.ABCServiceImpl" />
Will spring create 2 instances with different ids for the above configuration?If yes then although both the bean definitions are singleton we still have 2 instances of the same object in the context. Would that mean that its not a singleton any more?

Yes. Two seperate instances will be created. Yes this is not a singleton anymore in a classical meaning (one instance per JVM) - (if ever was), however the created bean (each of them) has a singleton scope (in a Spring meaning). If you really want to assure that an object of a given class will be always a singleton (only one instance per JVM) see Correct way of making a singleton a Spring bean.
But the question is if you really need 'the real singleton'?!
See http://docs.spring.io/spring/docs/3.2.1.RELEASE/spring-framework-reference/html/beans.html#beans-factory-scopes

Yes, the object will no more be Singleton.
By default all Spring injected beans are Singleton, but if you define the same bean twice with two different ids then Spring will create two instances.

Related

CDI Instance Producer

The instances passed to my producer does represent effective beans?
#Qualif1
#Prodcues
B qualif1(#Any Instance<B> instances){
return instances.select(B1.class).get(); // Select instance of B1 which extends B
}
I am wondering if instances are already beans or only the selected one will be a bean managed by the container?
Thanks in advance
This does not depend on using instances, but on the scopes of the beans. A call to get works like any other injection point: if you get a prototype bean, a new instance of the bean gets created. If you get an eager singleton - it is already created before you call get.
It seems like your question stems from mixing up beans and instances of beans: the former are definitions (and are all, in a sense "managed" by the container), the latter are instances (which are in the direct sense "managed").
The ladder of abstraction goes like this:
class -> bean -> instance
So the "bean" is neither a class (although in some projects every bean is also a class) nor an instance (although in some projects every bean is also an instance).
Personally, I blame Spring for blurring the boundaries between the three, by encouraging usage of eager singletons for practically everything.

demystification required on chapter 1 of Spring in Practice book regarding singleton beans not maintaining state

I am learning Spring and have found the book Spring in Practice to be an awesome source. I don't understand Spring bean singleton scopes completely however. And what I read in the section of bean scopes has confused me a bit.
Here is a excerpt from that section:
As you request singleton beans from the container, Spring will create
instances and cache them if they haven’t been created; otherwise,
Spring will return already-existing instances from its cache.
Therefore, singleton beans in Spring often don’t maintain state
because they’re usually shared among multiple threads (such as in
servlet environments). For example, singleton services often have
references to singleton DAOs, and the DAOs might have references to
Hibernate SessionFactorys, which are threadsafe.
Now I don't know much about multithreading in Java so please pardon my ignorance. In the above excerpt where it says "Therefore, singleton beans in Spring often don’t maintain state because they’re usually shared among multiple threads"
1). What does this mean for domain objects? Can I have a domain object called User defined as a singleton scope in the spring context? What would happen?
2). I notice that mostly datasources and large configurations are usually in the spring xml file. I have a feeling my questions relating to state and beans defaulting to singletons is related to wiring only big parts of an application.
Can someone clarify this topic for me? An example would be really helpful.
Thank you in advance.
A Java class is a description of state and behavior. An instance of that class is a holder of state that can exhibit behavior. Therefore, this class
public class Foo {
private String bar;
public Foo(String bar) {this.bar = bar;}
public void print() {System.out.println(bar);}
public void setBar(String bar) {this.bar = bar;}
}
describes a data structure which has a String as state and print() and setBar(String) methods as behavior. If you create an instance
new Foo("the state");
You now have an actual data structure that holds the String data (or state) "the state" and that can display that data by invoking the print() method or change it with setBar(String).
The problem with the class above is that it is mutable, ie. its state can change. If multiple threads are operating on it, you might see unexpected behavior. For example, one thread changes bar's value before another thread has the chance to print() out its previous value.
What does this mean for domain objects? Can I have a domain object
called User defined as a singleton scope in the spring context? What
would happen?
This means the exact same thing for domain objects as it does for service or presentation objects. You can very much have a domain object of type User defined as singleton scope in the Spring context. If you want to is a different question. Do you want your application to only ever have access to that one User instance? No, then don't make it singleton. Yes, then make it singleton. This only applies if Spring is actually managing the instances for you.
More clarifications:
It's important to understand what a Singleton is. Wikipedia says
restricts the Instantiation of a class to one object
If we are taking about restricted in regards to a JVM, a Singleton could be implemented as described here. If we are talking about restricted in regards to a Spring ApplicationContext, then we are talking about a Spring managed singleton scope bean (read the chapter carefully). For example
<bean id="customBean" class="org.mine.CustomBean" />
which is retrieved like
(CustomBean) context.getBean("customBean");
// or
context.getBean(CustomBean.class);
If we are always retrieving the instance from Spring's ApplicationContext, we are effectively only ever instantiating the class once.
So if that variable is being accessed by different parts of the
application, the state of the object can be changed by that variable
by executing for instance the setter methods on that variable. But
that seems like a singleton to me.
A web application is multi-threaded. If each thread is accessing the singleton bean and mutating it, you might get lost updates. These are typically not desired since you cannot predict them and therefore are hard to test.
That variable can be used to keep changing the same data structure
throughout different parts of the application. So how is the Foo
object not a singleton?
As stated earlier, Singleton is a pattern that describes how an instance is unique in regards to some context. Simply doing
new Foo("the state");
doesn't make that object a singleton. It's how you use it that makes it a singleton.
Well, if multiple threads change the same object at the same time, they'll interfere with each other. Most spring applications harness the power of multiple threads.
A singleton scoped bean corresponds to a single object (hence the name). Everyone asking for that bean will get the same object.
Therefore, you should not change that shared object.
What does this mean for domain objects? Can I have a domain object called User defined as a singleton scope in the spring context? What would happen?
Sure you could declare a bean of type user, but - as we learned above - everyone asking for that bean will get the same user object. Is this really what you want? For instance, if the bean is intended to represent the logged in user, this design would imply that only a single user can log in ...
On the other hand, if the bean merely holds configuration data that equally applies to all users, it would be quite reasonable to for the threads to share the same object (of course, if they change it, synchronization is required to prevent interference).
I notice that mostly datasources and large configurations are usually in the spring xml file.
That is indeed the typical use. Data that should be different for each thread is typically kept in local variables (or objects reachable from there). Because local variables are different for each method invocation, interference by other threads is not possible.
You can also use spring to manage short lived objects by declaring beans with a short-lived scope (such as session or request scope in a servlet environment) - though in that case, you'll have to take care that different threads don't access the state of the same object at the same time. With request scope, that's usually easy because requests are usually processed by a single thread. With session scope, you'll actually have to synchronize access.

spring bean properties with singleton

Need clarification on spring singleton .I have three objects ,these are readonly so never changed values.
I am planning to create these objects with singleton bean as properties.
My question: When spring creates these objects,everytime it will create new object when bean calls or once in life time it will call and create those objects?. What are the possible threading issues if any?
It depends on what you say to Spring to do. Spring has an Inversion Of Control container that manages the instances of the objects. Depending on the scope you give to your objects, it will make them singletons or not.
More info:
http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch04s04.html

Spring prototype scope - Use Cases?

I have clear understanding of the various scopes of Spring beans. But I am looking for some use cases of prototype scope of a bean in enterprise tier projects. It would be great if you can share some real life use cases of the prototype scope (not the request scope).
As someone who previously worked at SpringSource and have talked to the developers on this topic. Here is my take. Prototype is great for testing things out, hence the name prototype and not create new or something more description of creating a new instance of the bean each and every time you request it from the Spring container.
I have also found in my use over the years that I cannot think of any other place where prototype makes sense in any real-world production application. If your object holds state, it typically shouldn't be a Spring bean. I have found in all the applications I have worked on that all beans are Services, Repositories, and Singleton non state holding objects where I need to add features like Transactionality, JPA, JMS and the likes that give us the enterprise features that POJOs don't have.
The objects in my system that hold state are my Entities and View DTOs maybe, or other things that just make no sense to be a Spring Bean. So therefore in my applications in production there hasn't been a single "prototype" bean.
I used prototype beans to declare configured form elements (a textbox configured to validate names, e-mail addresses for example) and get "living" instances of them for every form being created in my webapp. The details are not important, only the principle, that I would summarize this way:
There is a class that has many config parameters
You need to create instances of it with a set of predefined configuration (fancy1, fancy2, stc.)
Think of the applicationContext.getBean("myBeanConfiguredFancy1") as a kind of factory method that creates the instance as preconfigured in the xml
I have used prototype mostly in conjunction with spring lookup-method. My application is a game server that needs to decode incoming bytes at tcp port. Consider the following bean definition
<bean id="channelBufferProtocol" class="org.menacheri.protocols.impl.ChannelBufferProtocol">
<lookup-method name="createLengthBasedFrameDecoder" bean="lengthFieldBasedFrameDecoder"/>
<property name="eventDecoder" ref="eventDecoder"></property>
<property name="lengthFieldPrepender" ref="lengthFieldPrepender"></property>
<property name="eventEncoder" ref="eventEncoder"></property>
</bean>
Inside the protocol implementation class, I have the following code to create the frame decoder pipeline.addLast("lengthDecoder", createLengthBasedFrameDecoder()); When this method is invoked, spring will create a new frame decoder instance and return it.
The bean returned by bean="lengthFieldBasedFrameDecoder" needs to be of scope prototype, since it is a stateful bean in my app.
Note: A protocol is nothing but a specific set of decoders and encoders chained together. "Chain of responsibility" design pattern.
We can use prototype scope in case of model classes(also called as Entities in hibernate) as application need different instances of model class for each thread/request.

Instantiating spring bean objects

I've been playing with Spring and had a quick question...
I have a loop within class A which instantiates new objects of class B. To do this I've used the new operator however I cannot reference any Spring beans injected into instances of class B as I get a null pointer exception. I think I understand that this would be due to spring not managing these instances as beans and therefore not being able to manage the lifecycle however I was just wondering what the best way to go about creating multiple instances would be i.e. should I used appContext.getBean("beanA"); ?
First - are right with your assumptions. Using new means spring doesn't manage the object.
Solutions can be:
appContext.getBean("beanA"), where the bean is of scope "prototype". You obtain the appContext by injecting it, or by implementing ApplicationContextAware
using #Configurable and apsectJ weaving. That way even objects instantiated with new become managed by spring (the weaver plugs into the compiler or the vm)
using a lookup-method - it's the same as the first option (again requires prototype-scoped bean), but you get a method of your class that returns a new instance each time you call it.
Normally, however, you shouldn't need that. In the rare cases you do, I'd recommend the 3rd option.

Categories

Resources