Wiring Spring Beans

The process of creating association between various object (beans) of an application, in the Spring container is called as wiring.

Springs provides 2 different approaches for wiring beans together:
  • Wiring through XML
  • Wiring through Java Class

Sample Java Classes

Shown below are the java classes we will be using to understand the two ways of bean wiring. There are two versions of Student class shown below. We will be using the first one for wiring using constructor injection and the second one for wiring using setter injection.

package examples.wiring;

import java.util.List;

public class Student {
	
    private String name;
    private Class cls;
    private List<String> subjects;
    private List<Award> awards;
	
    public Student(String name, Class cls, List<String> subjects, List<Award> awards){
	this.name = name;
	this.cls = cls;
	this.subjects = subjects;
	this.awards = awards;
    }
}

package examples.wiring;

import java.util.List;

public class Student {
    
    private String name;
    private Class cls;
    private List<String> subjects;
    private List<Award> awards;
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public Class getCls() {
        return cls;
    }
    
    public void setCls(Class cls) {
        this.cls = cls;
    }
    
    public List<String> getSubjects() {
        return subjects;
    }
    
    public void setSubjects(List<String> subjects) {
        this.subjects = subjects;
    }
    
    public List<Award> getAwards() {
        return awards;
    }
    
    public void setAwards(List<Award> awards) {
        this.awards = awards;
    }
}

XML Wiring

Shown below is the xml file used for wiring our objects:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    
    <bean name="cls" class="examples.wiring.Class" />
    <bean name="rockstar" class="examples.wiring.award.RockStarAward" />
    <bean name="topper" class="examples.wiring.award.TopperAward" />
    
    <bean name="student" class="examples.Student">
        <constructor-arg value="Robin"/>
        <constructor-arg ref="cls" />
        <constructor-arg>
            <list>
                <value>English</value>
                <value>Physics</value>
                <value>Maths</value>
                <value>Biology</value>
            </list>
        </constructor-arg>
        <constructor-arg>
            <list>
                <ref bean="rockstar" />
                <ref bean="topper" />
            </list>
        </constructor-arg>
    </bean>    
        
</beans>

For wiring with xml approach, we need to create an xml with the root element as '<beans>'. In the above xml we had created 4 beans. First three (cls, rockstar and topper) are straight forward. The student bean is a bit more involved and requires a bit of explanation. We are wiring this bean using the constructor injection.

  • To wire the name field of Student, we use the 'value' attribute to directly pass the string value 'Robin'.
  • For the 'class' field, we pass a reference of the class object using the 'ref' attribute
  • The 'subjects' field is of list type, to pass a list of values we had used the <list> tag, and a list of string values inside the <list>.
  • The 'awards' field is also of list type, but here we had passes a list of reference of awards object, hence used the 'ref' tag within <list>.

We can also use <set> in instead of <list>. The main difference between <list> and <set> is that any duplicate values used in <set> will be discarded. However in either case, they can be wired to a List of Set or even an array in Java.

The code below demonstrates wiring with setter injection. It used the <property> to wire different fields using their setter methods. Notice that <set> is used instead of <list> for wiring subjects.

<bean name="driver" class="examples    ">
    <property name="name" value="Robin" />
    <property name="cls" ref="cls" />
    <property name="subjects">
        <set>
            <value>English</value>
            <value>Physics</value>
            <value>Maths</value>
            <value>Biology</value>
        </set>
    </property>
    <property name="awards">
        <null />
    </property>
</bean>

There may be a situation where a student may not have won any awards. Notice that '<null>is used with awards. As we can easily guess, it is used to inject null value into the awards field.


Java Config (Wiring Beans With Java Class)

To wire beans using java, we need to create a Spring Configuration class and annotate the class with @Configuration as shown in the example below. This annotation tells Spring that beans are configured in this class and wiring should be done using this class.

In the configuration class we will create methods annotated with @Bean. These methods are used to configure a bean. We can use the name attribute in the @Bean annotation to give the bean a name. By default the name of the method is used as the bean name. The object returned by the @Bean annotated method serves as our Spring bean.

package examples.wiring;

import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeanConfig {
    
    @Bean(name="cls")
    public Class clasz(){
        return new Class();
    }
    
    @Bean 
    public RockStarAward rockstar(){
        return new RockStarAward();
    }
    
    @Bean 
    public TopperAward topper(){
        return new TopperAward();
    }
    
    @Bean
    public Student student(){
        List subjects = new ArrayList();
        subjects.add("Maths");
        subjects.add("English");
        return new Student("Robin", clasz(), subjects, null);
    }
}

Importing Configurations

Spring provides the flexibility to segregate the configuration files/classes in multiple places and import them to another configuration file / class.

Shown below is the syntax to import an xml configuration file into another config xml.

<import resource="cd-config.xml" />

To import a java configuration class into another configuration class below syntax can be used:

@Configuration
@Import(AnotherConfig.class)
public class CDPlayerConfig {
 ...
}

Mixing Configurations

Spring configurations can also be mixed. We can import a java config class in an xml config file and vice versa.

To import an xml configuration file into a java configuration class we can use the @ImportResource annotation as shown below:

@Configuration
@ImportResource("classpath:xml-config-file.xml")
public class JavaConfig {
	...
}

To import a java configuration class into an xml config file we just need to define it as a bean in the xml config file:

<bean class="soundsystem.CDConfig" />

Apart from the two approaches of wiring discussed above, Spring also provides the capability to wire beans automatically. In Automatic bean wiring beans can be discovered and wired automatically.

POPULAR ARTICLES

Creating Conditional Beans in Spring

The concept of condition beans enables Spring to restrict the creation of any bean depending on the evaluation of a condition. These beans get created only when a preset condition is evaluated as true

View Article

Accepting Request Param and Path Variable in Spring Controller

Spring MVC provides various ways through which a client browser can pass data to the Controller. In this article we will discuss about accepting Request Parameters and Path Variables in Spring Contr..

View Article

Generate Namespace & Schema Information using JAXB

Most xml documents used in enterprise applications makes use of namespace to avoid element name conflicts. This article talks about generating these namespace and schema information when marshaling...

View Article

Switching Database Profile using Spring Profiles

We are most likely to have separate db configuration for different environment like development and production environment. Spring profiles provide a convenient way to switch db profiles at runtime.

View Article

SQL and its Sub-Languages

SQL (Structured Query Language) is a language understood by most modern databases. It is an ANSI (American National Standard Institute) standard language which is used to manipulate databases.

View Article

Introducing JUnit Rule

Junit Rules allows developers to add additional functionalities that can applied to all test methods in a test class. It is similar to the concept of custom test runners but with reduced restrictions.

View Article

Addressing Ambiguity in Spring Autowiring

Spring autowiring is powerful concept, but we should be very cautious while using it. We may end up in creating ambiguity while autowiring beans, which will cause autowiring to fail.

View Article

Creating and Using Synonym in Oracle Database

Synonyms are database objects used to provide duplicate names to existing objects in the database. It is just an alternate name used to hide the original name of the object.

View Article

Creating and Using Sequence in Oracle Database

A sequence is used to auto-generate numbers in ascending or descending order which can serve as a primary key or a part of it (in case of composite key).

View Article

Creating and Manipulating Constraints in Oracle Database

Constraints are used to impose certain rules on columns to avoid invalid data entry into the table. If any of the constraint is violated the operation fails.

View Article

Integrating Log4J with Perf4J for Performance Logging

Perf4j is an open source logging framework used primarily for monitoring performance statistics in java applications. Log4j has the ability to integrate with perf4j to capture performance data.

View Article

Tagging in GIT

Tagging allows us to mark a specific point in the commit history or snapshot. A tag is typically used to mark a project release. This article shows how to create tags in Git.

View Article