You already know how to initialize the bean in the Spring container using the XML file in the previous tutorial. In addition to this, Spring also supports us to initialize the bean using the @Configuration annotation in the Java code. Let’s see how to initialize the bean in the Spring container using the @configuration annotation in this tutorial.
First, I will create a Maven project as follows:
Spring dependency:
1 2 3 4 5 |
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>6.0.2</version> </dependency> |
Now, I will add a HelloWorld object in the com.huongdanjava.springconfiguration package so that it can print out a “Hello World” message as follows:
1 2 3 4 5 6 7 8 |
package com.huongdanjava.springconfiguration; public class HelloWorld { public void print() { System.out.print("Hello World!"); } } |
To declare this HelloWorld object in the Spring container using the @Configuration annotation, you create a new class using the @Configuration annotation as follows:
1 2 3 4 5 6 7 8 |
package com.huongdanjava.springconfiguration; import org.springframework.context.annotation.Configuration; @Configuration public class ApplicationConfiguration { } |
then declare the HelloWorld object as a bean in the Spring container using the @Bean annotation as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.huongdanjava.springconfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ApplicationConfiguration { @Bean public HelloWorld helloWorld() { return new HelloWorld(); } } |
OK, so we have successfully declared the HelloWorld bean in the Spring container, the bean id is the name of the method.
Now, to call this bean and print the “Hello World” message, you can code like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.huongdanjava.springconfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Application { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class); HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld"); helloWorld.print(); } } |
Note that here we use another implementation of the ApplicationContext: AnnotationConfigApplicationContext.
Result: