top of page
index-1-1.jpg

Spring Framework: Declaring Beans

In Spring framework when you have to use a bean you have to declare it first. This technique is called wiring and it is the main idea behind dependency injection. In this article we will talk about declaring beans. Lets get started.


Step 1: First of all configure Spring to tell it what beans to declare and how those beans will be linked to each other. For this purpose we will create an xml file as given below:

<?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">

<Beans declaration goes here>

</beans>

It is a typical Spring configuration file. All the beans declaration with tag <bean/> will go inside <beans></beans>


Step 2: Now we will define our class and declare it as bean in spring configuration. We also will declare an interface that our class will be implementing.


Interface:

package com.aurora.spring.beans;
public interface Writer {
	void write();
}

Implementation:

An EnglishWriter that will print some greetings in English.

package com.aurora.spring.beans;
public class EnglishWriter implements Writer{
	public void write() {
		System.out.println(“Hello, how are you?”);
        }
}

A SpanishWriter that will print some greetings in Spanish.

package com.aurora.spring.beans;
public class SpanishhWriter implements Writer{
	public void write() {
		System.out.println(“Hola, como estas?”);
        }
}

Step 3: Now we will declare those beans in spring configuration file.

<bean id=“english” class=”com.aurora.spring.beans.EnglishWriter” />
<bean id=“spanish” class=”com.aurora.spring.beans.SpanishWriter” />

Step 4: Now we will load the spring container to get the beans that were declared to use them. We will load configuration file from class path.

ApplicationContext ctx = new ClassPathXmlApplicationContext("com/aurora/spring/application-context.xml");

Step 5: Get the bean from container and execute its method.

Writer writer = (Writer) ctx.getBean("english");
writer.write();

Similarly we can get SpanishWriter bean and execute its code.

Link to this project can be found below. It is a maven project. To run the project you have to import it in Spring Tool Suite, compile it and go to Main.java class and run that class. Output can be seen in STS’s console.

In the next article we will cover injection of beans.

Link to the code repository: https://github.com/aurorablogs/spring-declaring-beans

31 views0 comments

Comments


bottom of page