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
Related
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.
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.
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.
I am wiring my UserService type classes using spring's IOC.
But what about my User class?
I have a interface User, then a UserImpl class.
In my controller action's do I just do:
User u = new UserImpl();
Or would it sometimes make sense to use IOC for this also?
Sometimes I use a different constructor also when instantiating a class, based on some conditions. I guess your stuck in these situations?
It will not make sense to use dependency injection or IOC for your business objects like User because business objects are not the dependencies of the class they are the part of the class using them.
Spring IOC, by default, will create Singletons for you. Which means all user threads using your app will share that single instance of class. This is generally fine for Service type classes. If needed this singleton behavior can be changed to object per request (prototype), but this will cause you to change this setting for the users of the non-sigleton object as well.
Domain/business classes are state-full, it's easiest to create such objects once-per-request in order to avoid concurrency issues.
I am having an issue when trying to create beans from a spring Application Context inside a bean instantiated by spring using constructor arguments.
I have implemented the ApplicationContextAware interface but it populates the context after the instance is created (obvious).
But then, if you need to get beans from the constructor, and I am talking about a variable number of objects defined at runtime, what would be the correct way to proceed?
In beans instanciated by Spring, instead of initializing it in the Constructor, initialize it in a dedicated method, marked as "init-method" for Spring.
You have about the same effect as initializing in the constructor, but you are using the correct Spring life-cycle.
You can make the context accessible from constructor exploiting aspect-oriented programming. Spring has special support for that - #Configurable(preConstruction = true).
Feel free to read more about that at the spring reference - 6.8.1. Using AspectJ to dependency inject domain objects with Spring