Occasionally, we need to instate assets in the bean classes. For instance, this is possible by making database associations or approving third-party services at the season of initialization before any customer request. Spring Framework gives distinctive courses through which we can give post-introduction and pre-annihilation techniques in a Spring bean life cycle.
These are as follows:
- By actualizing the InitializingBean and DisposableBean interfaces—both of these interfaces announce a solitary strategy where we can instate/close assets in the bean. For post-instatement, we can execute the InitializingBean interface and provide an implementation of the afterPropertiesSet() function. For pre-destroy, we can actualize the DisposableBean interface and provide an implementation of the destroy() function. These functions are the callback techniques, which are similar to servlet audience implementations. This functionality is easy to utilize, yet it's not recommended, as it will cause tight coupling with Spring Framework in our bean implementations.
- Giving init-function and destroy-function quality values for the bean in the Spring bean configuration file. This is the prescribed functionality as there's no immediate dependency to Spring Framework. We can also make our own functions.
Both the post-init and pre-destroy functions shouldn't have any contentions, but they can throw exceptions. We would also have to get the bean occasion from the Spring application setting for these functions.
Let's see an example of the life cycle of a bean. Here, we'll look at how to initialize and destroy the bean function. Reuse the previous project and modify the bean XML configuration file as follows:
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="userGreeting" class ="ktPackage.UserGreeting" init-function = "afterPropertiesSet"
destroy-function = "destroy"/>
</beans>
Now add two functions in UserGreeting.kt:
class UserGreeting {
private var globalGreeting: String? = "Sasuke Uchiha"
fun setGreeting(greeting: String) {
globalGreeting = greeting
}
fun getGreeting() {
println("Welcome, " + globalGreeting!! + "!!")
}
fun afterPropertiesSet(){
println("Bean is going to start.")
}
fun destroy(){
println("Bean is going to destroy.")
}
}
Call registerShutdownHook() after the task is completed in the main function of the class:
fun main(args: Array<String>) {
val context = ClassPathXmlApplicationContext("Beans.xml")
val objectA = context.getBean("userGreeting", UserGreeting::class.java)
objectA.setGreeting("Naruto Uzumaki")
objectA.getGreeting()
context.registerShutdownHook()
}
The output will be as follows:
Bean is going to start.
Welcome, Naruto Uzumaki!!
Bean is going to destroy.