Can we undeploy a Spring container managed bean which is no more needed - spring

I a get a get a bean from Spring container say
MyClass obj1 = Context.getBean("obj1");
After using obj1, I am sure that it will not be needed in rest of my application.
Then is there any way to ask Spring container to destroy the bean.
Atleast giving hint to Spring container that it is no more needed and spring my decide whether to destroy it or not (Similar to garbage collection)?

Make "obj1" a prototype-scoped bean. Then Spring will create a new instance of it each time you ask for it (make sure you are ok with this), and then it will not manage the instance any further, so when you are done with it and release all your references it can be garbage collected.
Prototype scope is like new, only giving you Spring-configured beans.

I don't think it will be possible for you to tell Spring container to destroy that bean. If you notice most of these beans created by Spring framework are Singleton that are supposed to give you same instance of the bean every time you get it injected into your code. A singleton by nature is supposed to live through the life of the application hence it cannot be destroyed.

Related

Getting Spring object instantiation right

I'm new to Spring and a little confused about how it works. I get that I can use the application context to instantiate beans and have them populated. However, is the idea that I should be able to just write Bean b = new Bean() and then have Spring to somehow automagically populate that Bean?
I'm experimenting with Spring in a web application, and as far as I can see I need to inject the ApplicationContext into, say, the servlets to be able to instantiate other beans (services, daos etc.) from there. It's a bit cumbersome, but probably works.
However, is Spring meant to be able to hook into any object instantiation which happens on classes defined as beans in applicationContext.xml?
Spring is an Inversion of Control container. A bean is an object whose life cycle is managed by Spring. If you want Spring to populate an object, it needs to go through Spring, ie. it needs to be bean.
is Spring meant to be able to hook into any object instantiation
which happens on classes defined as beans in applicationContext.xml?
Spring doesn't hook into anything. You configure your beans and the relationships between them with Spring and Spring handles creating the instances and linking them up.
For domain objects, Spring provides a solution via the #Configurable annotation: http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#aop-atconfigurable
It requires compile- or load-time-weaving and, thus, introduces some additional complexity but having the convenience of using the standard new Bean() syntax plus Spring's autowiring is worth it in my opinion.
Alternatively, you could define your domain objects as beans with prototype scope and use some factory to create them using the Spring ApplicationContext.getBean() method. With a scope of prototype a new instance will be returned every time and since you go through the ApplicationContext, Spring will do all the dependency injection magic as usual.
As for services and other beans with singleton scope, you would typically NOT retrieve them by first injecting the ApplicationContext and using it but instead you would inject them via either a constructor, setter or annotation-based strategy. The documentation covers that in detail: http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#beans-factory-collaborators

Spring #PreDestroy method

I found out that #PreDestroy only work with singleton scoped bean. I was thinking what could go wrong if we use it with prototype scoped bean. Anything at all??? I dont think so. I think this is just not implemented in spring as they would have to keep the references to all the beans created. Tell me if i am wrong
Spring can only initialize/destroy beans it also controllers and basically prototype scoped beans aren't under the control of spring (after construction). It doesn't know when it is cleaned up, destroyed or what so ever. As such the #PreDestroy method isn't callable for prototype beans (as they do not have a clearly defined lifecycle like singletons or request scoped beans).
For "prototype" scoped beans, Spring does not call the #PreDestroy method.
Here is the answer from the Spring reference manual. Section 7.5.2
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-scopes-prototype
In contrast to the other scopes, Spring does not manage the complete lifecycle of a
prototype bean: the container instantiates, configures, and otherwise assembles a
prototype object, and hands it to the client, with no further record of that prototype
instance.
Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding.
To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up.
The #PreDestroy annotation does not belong to Spring, it’s located in the jsr250-api library jar under javax.annotation package.
By default, Spring will not aware of the #PreDestroy annotation. To enable it, you have to either register CommonAnnotationBeanPostProcessor or specify the <context:annotation-config /> in bean XML configuration file.

Does spring internally do a getBean on the property refs it needs to load?

When i want a bean say in the main method I ask for a getBean on the id. Does spring container do the same when we define properties as refs to other beans within a single bean ?
Does spring container do the same when we define properties as refs to
other beans within a single bean
Ultimately yes, Spring does find beans within the application container which match your bean definition. How it does it is something which shouldn't be too much of a concern to most users. Since it's usually enough to know that if you ask for a bean from Spring it'll come wired with all of it's dependencies.
If you're interested in the exact wiring mechanism the source code is the place to learn.

Stateful beans and Stateless beans in Spring context

I am reading spring through its official documentation and at one place I came to a line that uses prototype scope for all stateful beans while singleton for stateless beans.
I know there is something as stateful as well as stateless beans in EJB but this is not what they have mentioned in the documents.
Can anyone explain to me what exactly this means of stateful as well stateless beans in Spring
Thanks in advance
From spring perspective
stateless beans: beans that are singleton and are initialized only once. The only state they have is a shared state. These beans are created while the ApplicationContext is being initialized. The SAME bean instance will be returned/injected during the lifetime of this ApplicationContext.
stateful beans: beans that can carry state (instance variables). These are created EVERY time an object is required (like using the "new" operator in java).
These are not EJB statfull/stateless session beans.
There is no point in storing specific information like client data, per request data in Singleton bean as they are created only once by Spring IOC container. That's why singleton beans are stateless. They are shared resources. They can only be used for storing global information.
When a request is made for creating a prototype bean, a new request is created every time. So, they can be used to store some specific information for each request. So they are stateful.
It totally depends on the implementation. See tomee for example http://tomee.apache.org/statelesscontainer-config.html . You'll have to check in your server docs

Can the object created in IoC container be called Singleton. If not - why?

can the object created in IOC container can be called Singleton if yes why if no why?
Can anybody explain me in detail in simple words how IOC conatiner exactly manages the objects..
You can say that a spring singleton is not a singleton.
Singleton has its meaningful scope, the spring singleton scope is the spring ioc container. And the classic singleton's meaningful scope is the ClassLoader. You may find more about the distinction between these kinds of singleton here: A spring singleton is not a singleton.
Spring manage its singleton in a hashmap(Singleton Cache). When you get a bean from the spring ioc container, it first checks if the bean has already exists in the singleton cache, if does, it returns the bean from the singleton cache
Spring (and other ioc-containers) offer different scopes. One of the scopes is singleton - i.e. the container instantiates the object only once and gives / injects only one instance. Singleton is the default scope, so most of the beans are indeed singletons from the point of view of the container- i.e. they have only one instance in it.
However, there are other scopes, like prototype or the web-based request and session.
In managing the bean, the container does the following:
invokes the #PostConstruct and #PreDestroy methods (or the init and destroy methods, configured by any available means)
injects all their defined dependencies (=sets other beans existing in the container to the fields of this bean)
creates AOP aspects around the bean methods
Note: you can instantiate more than one objects of a class that is defined as as singleton bean. The container instantiates the object only once, but your code is not limited to instantiating it multiple times.
can the object created in IOC
container can be called Singleton if
yes why if no why?
Read this, from the Spring Reference.
Can anybody explain me in detail in
simple words how IOC conatiner exactly
manages the objects..
Read this, from the Spring Reference.
I use a more generic definition of a Singleton:
A Singleton is an object that is
guaranteed to be unique inside a given
scope.
This scope is the ClassLoader in the traditional singleton definition, but other possible scopes are:
Application (may be clustered and therefor classic Singleton won't help)
HTTP Session
Thread (implemented through ThreadLocals)
HTTP Request etc.
(I really like the Seam method Component.getInstance(Class, ScopeType) that lets you choose the Scope you want a singleton for.)
You might find this Google Groups thread useful.

Resources