The @Configuration and @Bean annotations

The use of the @Configuration annotation on a class, implies that this class will be utilized by the Spring IoC container and will be considered a source of bean definitions.

The use of a @Bean annotation on a function means the function will return an object that's enrolled as a bean in the Spring application context.

Here's a sample code of @Configuration and @Bean:

@Configuration
open class CodeBasedConfiguration{
@Bean
open fun mainApp(): MainApp{
return MainApp()
}
}

The previous code will be equivalent to the following XML configuration:

<beans>
<bean id = "mainApp" class = "MainApp"/>
</beans>

Here, the function name is commented on with the @Bean annotation, which creates and returns the bean definition. Your configuration class can have a presentation for in excess of one @Bean.

The content of GreetingConfigurationConfBean.kt is as follows:

@Configuration
open class GreetingConfigurationConfBean{
@Bean
open fun greeting(): GreetingConfBean{
return GreetingConfBean()
}
}

The content of GreetingConfBean.kt is as follows:

class GreetingConfBean{
private var users: String? = null
fun setUsers(users: String) {
this.users = users
}
fun getUsers() {
println("Welcome, $users!!")
}
}

The content of MainAppConfBean.kt is as follows:

fun main(args: Array<String>) {
val applicationContext = AnnotationConfigApplicationContext(GreetingConfigurationConfBean::class.java)

val greeting = applicationContext.getBean(GreetingConfBean::class.java)
greeting.setUsers("Naruto Uzumaki")
greeting.getUsers()
}

The result will be as follows:

Welcome, Naruto Uzumaki!!
..................Content has been hidden....................

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