Initialize bean in Spring container using @Configuration annotation

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:

Initialize bean in Spring container using @Configuration annotation

Spring 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:

To declare this HelloWorld object in the Spring container using the @Configuration annotation, you create a new class using the @Configuration annotation as follows:

then declare the HelloWorld object as a bean in the Spring container using the @Bean annotation as follows:

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:

Note that here we use another implementation of the ApplicationContext: AnnotationConfigApplicationContext.

Result:

Initialize bean in Spring container using @Configuration annotation

5/5 - (2 votes)

Add Comment