1annotation inversion of control, bean scope
Last updated
Was this helpful?
Last updated
Was this helpful?
Bean Scope
Default Scope: Singleton
Spring Container creates only one instance of the bean, by default
It is cached in memory
All requests for the bean will return a SHARED reference to the SAME bean
e.g.
You can add custom code during bean initialization
Calling custom business logic methods
Setting up handles to resources(db, sockets, file etc)
You can add custom code during bean destruction
Calling custom business logic method
Clean up handles to resources(db, sockets, file etc)
Any method name. Must be "public void".
Any method name. Must be "public void".
Define your methods for init and destrop
Configure the method names in Spring config file
Defining init and destroy methods
When you are defining init and destroy methods should follow these rules:
The methods should be public void.
The methods should be no-arg, meaning they shouldn't accept any method arguments.
For "prototype" scoped beans, Spring does not call the destroy method. Gasp!
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.
This also applies to both XML configuration and Annotation-based configuration.
What are Java Annotations?
Special labels/markers added to Java Classes
Provide meta-data about the class
Processed at compile time or run-time for special processing
Why Spring Configuration with Annotation?
XML configuration can be verbose
Configure your Spring beans with Annotations
Annotations minimizes the XML configuration
Spring will scan your Java classes for special annotations
Automatically register the beans in the Spring container
Enable component scanning in Spring config file
Add the @Component Annotation to your Java classes
Retrieve bean from Spring container
Step1: Enable component scanning in Spring config file
e.g.
Step2:
e.g.
Default bean id: the class name, make first letter lower-case.
e.g.Step3: Retrieve bean from Spring container