Singleton scope

The default scope is always a singleton. This is a bean definition of the Spring IoC container that returns a single object instance in every object initialization. Here's a piece of code for the singleton scope:

<!-- A bean example with singleton scope -->
<bean id = "..." class = "..." scope = "singleton"/>
<!-- You can remove the scope for the singleton -->
<bean id = "..." class = "..."/>

Let's take a look at an example of a singleton scope.

Create a Spring project in the IDE. To do this, create two kt files and a bean XML configuration file under the src folder. 

Here's a piece of the code of CreateUserGreeting.kt:

class UserGreeting {
private var globalGreeting: String? = "Sasuke Uchiha"

fun setGreeting(greeting: String) {
globalGreeting = greeting
}

fun getGreeting() {
println("Welcome, " + globalGreeting!! + "!!")
}
}

The content of BeansScopeApplication.kt is as follows:

fun main(args: Array<String>) {
val context = ClassPathXmlApplicationContext("Beans.xml")

// first object
val objectA = context.getBean("userGreeting", UserGreeting::class.java)

// set a value for greeting
objectA.setGreeting("Naruto Uzumaki")

objectA.getGreeting()

val objectB = context.getBean("userGreeting", UserGreeting::class.java)
objectB.getGreeting()
}

The following is the beans.xml configuration file:

<?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" scope="singleton"/>

</beans>

After running this project, you will find this output:

Welcome, Naruto Uzumaki!!  <--- value of objectA 
Welcome, Naruto Uzumaki!! <--- value of objectB
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.174.0