Bean life cycle

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:

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.