Spring Bean Injection Example

 

In this example, we will see how to perform the dependency injection of a bean in Spring.

 

1. Project structure

Spring-Bean-Injection-Example

 

2. Spring beans

We consider the following classes :

Address :

 

Person :

 

The Person class has a dependency on the Address class.

In this example, we will use the Setter-based DI.

 

3. Beans definition

Now, we will supply the beans configuration to the container.

 

Since the address bean is a dependency of the person bean, in the person configuration, we set the value of the address property to be a reference to the address bean.

The address  bean is also called collaborator

 

We can also define the address bean directly inside the property element of the person bean, so the <bean/> element is called inner bean

In this case, we don’t need to specify an id or a name for the inner bean, because it is only visible by the enclosing bean.

 

The person2 define an inner bean to initialize the address property.

 

4. Test It

 

Output :

 

 

Download  source code