DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Trending

  • Using Python Libraries in Java
  • What’s Got Me Interested in OpenTelemetry—And Pursuing Certification
  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • Proactive Security in Distributed Systems: A Developer’s Approach
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring XML-Based DI and Builder Pattern

Spring XML-Based DI and Builder Pattern

This quick tutorial covers creating Spring beans for classes created with the Builder pattern using XML.

By 
Shamik Mitra user avatar
Shamik Mitra
·
Dec. 21, 16 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
25.7K Views

Join the DZone community and get the full member experience.

Join For Free

Recently, I faced a situation where a project was using Spring for its business layer and maintains the Spring dependencies in an XML file. They cannot upgrade this XML-based configuration to a Java-based configuration. It's an old project, it will take time, and they can't afford it.

That's fine, but the problem is that they want to add a third-party module to re-use some utilities from that library. When they try to incorporate the aforesaid module, they discovered that many classes that are exposed as services were created using the Builder pattern. So we will see how we can incorporate the Builder pattern in Spring XML-based DI.

Builder Pattern

The Builder pattern is used to create complex objects — which have some required and some optional parameters.

We create a static inner class called Builder and pass the required parameters in the constructor of that Builder. Then, set optional parameters calling the Setter method of that Builder.

Lastly, it has a build() method, which will produce the actual object.

Say we create an Employee object using the Builder pattern, where the id and the name of the employee are mandatory, but hobbies, gender, and address are optional.

package com.example.advanceSpring.entity;

public class Employee {   
    private Long id;
    private String name;
    private int gender;
    private String address;
    private String hobby;

    private Employee() {}

    public static class EmployeeBuilder{
        private Long id;
        private String name;
        private int gender;
        private String address;
        private String hobby;

        public EmployeeBuilder(Long id, String name) {
            this.id=id;
            this.name=name;
        }       

        public void setGender(int gender) {
            this.gender = gender;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public void setHobby(String  hobby) {
            this.hobby = hobby;
        }

        public Employee build() {
            Employee emp = new Employee();
            emp.id=id;
            emp.name=name;
            emp.gender=gender;
            emp.address=address;
            emp.hobby=hobby;
            return emp;
        }
    }

    @Override
    public String toString() {       
        return "Employee [id=" + id + ", name=" + name + ", gender="+( gender == 1?"Male":"Female") + ", address=" + address + ", hobby="
                + hobby + "]";
    }
}

Creating the Bean

Let's say this class comes from a third party JAR and we need to create an Employee object using Spring XML-based dependency injection.

How can we do that?

  1. Register the builder class using the context of Employee class with $. So the class attribute will be class =”com.example.advanceSpring.entity.Employee$EmployeeBuilder”. By doing this, Spring will understand that Employee builder is an inner class of Employee.

  2. Pass the required parameters using constructor-args.

  3. Pass the optional parameter using the property tag.

  4. Register the Employee bean in Spring XML. While registering, one thing you can notice is that the Employee object constructor is private, so the Spring bean can’t call it by reflection. So we will use the factory-bean and the factory-method attribute of Spring XML.

    The factory-bean attribute tells Spring to use the bean as a Factory class for creating the Object, so here, Spring treats EmployeeBuider as a Factory of Employee Object.

    The factory-method attribute tells Spring, upon calling the method instance of the Object, to return, so here, the build() method acts as a factory method to create the Employee Object.

    <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-2.5.xsd">
    
        <bean id="helloBean" class="com.example.advanceSpring.HelloWorld">
            <property name="name" value="Shamik" />
        </bean>
    
        <bean id="builder" class="com.example.advanceSpring.entity.Employee$EmployeeBuilder">
            <constructor-arg value="1"/>
           <constructor-arg value="Shamik Mitra"/>
           <property name="gender" value="1"/>
           <property name="hobby" value="Blogging"/>
        </bean>
        <bean id="employee" class="com.example.advanceSpring.entity.Employee" factory-bean="builder" factory-method="build"/>
    
    </beans>
    
  5. Now we will test the settings.

    import org.springframework.context.ApplicationContext;
    
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.example.advanceSpring.entity.Employee;
    
    public class SpringTest {
    
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext(
                    "SpringTest.xml");
    
            Employee employee = (Employee) context.getBean("employee");
            System.out.println(employee);
        }
    
    }
  6. Output:

    Employee [id=1, name=Shamik Mitra, gender=Male, address=null, hobby=Blogging]

Spring Framework Builder pattern

Published at DZone with permission of Shamik Mitra, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!