How do I convert Java Object to JSON?

To convert Java objects or POJOs (Plain Old Java Objects) to JSON we can use one of JSONObject constructor that takes an object as its argument. In the following example we will convert Student POJO into JSON string. Student class must provide the getter methods, JSONObject creates JSON string by calling these methods.

In this code snippet we do as follows:

  • Creates Student object and set its properties using the setter methods.
  • Create JSONObject called object and use the Student object as argument to its constructor.
  • JSONObject use getter methods to produces JSON string.
  • Call object.toString() method to get the JSON string.
package org.kodejava.json;

import org.json.JSONObject;
import org.kodejava.json.support.Student;

import java.util.Arrays;

public class PojoToJSON {
    public static void main(String[] args) {
        Student student = new Student();
        student.setId(1L);
        student.setName("Alice");
        student.setAge(20);
        student.setCourses(Arrays.asList("Engineering", "Finance", "Chemistry"));

        JSONObject object = new JSONObject(student);
        String json = object.toString();
        System.out.println(json);
    }
}

Running this code produces the following result:

{"courses":["Engineering","Finance","Chemistry"],"name":"Alice","id":1,"age":20}

The Student class use in the code above:

package org.kodejava.json.support;

import java.util.List;

public class Student {
    private Long id;
    private String name;
    private int age;
    private List<String> courses;

    // Getters and Setters removed for simplicity
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
        <type>bundle</type>
    </dependency>
</dependencies>

Maven Central

How do I inject beans, properties and methods using Spring EL?

Using Spring Expression Language (SpEL) we can inject object references or values into a bean dynamically when the bean is created instead of statically defined at development time. In this example you’ll learn how to inject a bean’s property using a property of another bean.

Let start by create two classes, the Student and Grade classes. The student object will have a property to store their grade name which will be obtained from the grade object.

package org.kodejava.spring.core.el;

public class Student {
    private String name;
    private String grade;

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }
}
package org.kodejava.spring.core.el;

public class Grade {
    private String name;
    private String description;

    public Grade() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

Next we create the spring configuration file. In this configuration we have two beans definition, the grade and student bean. We set the name and description property of the grade bean.

We also set the name property of student bean using a string literal. But the grade property value is set to the grade‘s bean name property using the Spring EL, #{grade.name}. The expression tells the spring container to look for a bean whose id is grade, read its name and assign it to student‘s grade.

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

    <bean id="grade" class="org.kodejava.spring.core.el.Grade">
        <property name="name" value="Beginner" />
        <property name="description" value="A beginner grade." />
    </bean>
    <bean id="student" class="org.kodejava.spring.core.el.Student">
        <property name="name" value="Alice" />
        <property name="grade" value="#{grade.name}" />
    </bean>

</beans>

And then create the following program to execute the spring container and retrieve the student bean from it.

package org.kodejava.spring.core.el;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELDemo {
    public static void main(String[] args) {
        try (ClassPathXmlApplicationContext context =
                     new ClassPathXmlApplicationContext("spel-example.xml")) {

            Student student = (Student) context.getBean("student");
            System.out.println("Name  = " + student.getName());
            System.out.println("Grade = " + student.getGrade());
        }
    }
}

This program will print the following output:

Name  = Alice
Grade = Beginner

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How to set and get properties of a bean in JSP?

In this example you will learn how to set and get the value of Java object properties that you define in a JSP pages. For this example, let’s first start by creating a variable that we named customer, that will have a type of Customer class. To create this variable we use the <jsp:useBean> action.

After we create the customer variable we can set the property value of the customer bean using the <jsp:setProperty> action. And to get the property value of the customer bean we use the <jsp:getProperty> action.

The name attribute in the setProperty and getProperty action refer to our customer bean. The property attribute tells which property we are going to set or get. To set the value of a property we use the value attribute.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Bean Property Demo</title>
</head>
<body>

<jsp:useBean id="customer" class="org.kodejava.servlet.support.Customer"/>
<jsp:setProperty name="customer" property="id" value="1"/>
<jsp:setProperty name="customer" property="firstName" value="John"/>
<jsp:setProperty name="customer" property="lastName" value="Doe"/>
<jsp:setProperty name="customer" property="address" value="Sunset Road"/>

Customer Information: <%= customer %><br/>
Customer Name: <jsp:getProperty name="customer" property="firstName"/>
<jsp:getProperty name="customer" property="lastName"/>

</body>
</html>

And here is the code for our Customer bean. This bean contains property such as the id, firstName, lastName and address.

package org.kodejava.servlet.support;

public class Customer {
    private int id;
    private String firstName;
    private String lastName;
    private String address;

    public Customer() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getAddress() {
        return address;
    }

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

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

We access the JSP page we will see the following output:

Customer Information: Customer{id=1, firstName='John', lastName='Doe', address='Sunset Road'}
Customer Name: John Doe
JSP Bean Property Demo

JSP Bean Property Demo

How do I define inner bean in Spring?

Inner bean is a bean defined inside another bean, it can be seen as an inner class. In another word, the inner bean is a bean defined within the scope of another bean. In this case the inner bean can only be use by the outer bean. No other bean in the Spring context can refer to that bean.

So, if you sure that a bean is only use within a single bean it is a good idea to use an inner bean. Inner bean can be injected through setter injection or constructor injection.

Here is an example of Spring configuration for an inner bean injection:

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

    <bean id="racer" class="org.kodejava.spring.core.Racer">
        <property name="car">
            <bean class="org.kodejava.spring.core.Car">
                <property name="maker" value="Ferrari" />
                <property name="year" value="2021" />
            </bean>
        </property>
    </bean>

</beans>

In this configuration we use a setter injection. So we use the property element. Instead of using a ref attribute for referring to another bean we define the bean using the bean element inside the property element. And then we create the Car bean and sets its properties.

If you want to use a constructor injection you can inject the Car bean into the Racer bean by defining a bean inside the constructor-arg element in the Racer bean.

Below is our Racer and Car classes.

package org.kodejava.spring.core;

public class Racer {
    private Car car;

    public Racer() {
    }

    public Racer(Car car) {
        this.car = car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    @Override
    public String toString() {
        return "Racer{" +
                "car=" + car +
                '}';
    }
}
package org.kodejava.spring.core;

public class Car {
    private String maker;
    private int year;

    public void setMaker(String maker) {
        this.maker = maker;
    }

    public void setYear(int year) {
        this.year = year;
    }

    @Override
    public String toString() {
        return "Car{" +
                "maker='" + maker + "'" +
                ", year=" + year +
                '}';
    }
}

Let’s create our Demo class to run the program:

package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo {
    public static void main(String[] args) {
        var context = new ClassPathXmlApplicationContext("inner-bean.xml");

        Racer racer = (Racer) context.getBean("racer");
        System.out.println("Racer = " + racer);
        context.close();
    }
}

Here is the output of our program:

Racer = Racer{car=Car{maker='Ferrari', year=2021}}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I inject into bean properties?

A bean usually have some private properties that can be accessed through a pair of accessor methods, the setters and getters. These setters, the setXXX() method can be used by Spring Framework to configure the beans.

This method of injecting beans property through their setter methods is called the setter injection. The following example will show you how to do it.

Below is our DrawingBean that have colour and shape properties. In the example we will inject both of the properties using their respective setter method. The configuration is done in the Spring application configuration file.

package org.kodejava.spring.core;

public class DrawingBean {
    private String colour;
    private Shape shape;

    public DrawingBean() {
    }

    public void drawShape() {
        getShape().draw();
        System.out.printf("The colour is %s.", getColour());
    }

    public String getColour() {
        return colour;
    }

    public void setColour(String colour) {
        this.colour = colour;
    }

    public Shape getShape() {
        return shape;
    }

    public void setShape(Shape shape) {
        this.shape = shape;
    }
}

We can inject a simple value into a bean, such as string, number, etc. We can also inject a reference to another bean. Here we define an example of other bean, the Rectangle bean that we will inject into the DrawingBean.

package org.kodejava.spring.core;

public interface Shape {
    /**
     * Draw a shape.
     */
    void draw();
}
package org.kodejava.spring.core;

public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle.");
    }
}

Let’s create the Spring application configuration file that will register our beans into the Spring context. After that we just create a simple program to execute it.

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

    <bean id="rectangle" class="org.kodejava.spring.core.Rectangle" />

    <bean id="drawingBean" class="org.kodejava.spring.core.DrawingBean">
        <property name="colour" value="Red" />
        <property name="shape" ref="rectangle" />
    </bean>

</beans>

In the configuration file above you can see that we use the property element to set a bean’s property. The name attribute is referring to the bean’s setter methods name, exclude the set prefix.

The value attribute of the property element is used to inject a simple value, such as string, int, etc. For injecting a reference to another bean we use the ref attribute instead.

package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DrawingBeanDemo {
    public static void main(String[] args) {
        try (var context = new ClassPathXmlApplicationContext("drawing-bean.xml")) {
            DrawingBean bean = (DrawingBean) context.getBean("drawingBean");
            bean.drawShape();
        }
    }
}

Here are the output of our example:

Drawing a rectangle.
The colour is Red.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I initialize and destroy beans in Spring?

When creating an instance of a bean you might need to do some initialization to the bean. Likewise, when the bean is no longer needed and removed from the Spring container you might want to do some cleanup routine or destroy the bean.

To do this initialization and destroy routine you can use the init-method and destroy-method attribute when declaring a bean in spring configuration using the <bean> element.

By defining the init-method and destroy-method it will allow the Spring Container to call the initialization method right after the bean created. And just before the bean removed and discarded from the container, the defined destroy method will be called. Let’s see some code snippet as an example.

package org.kodejava.spring.core;

public class AutoEngine {
    public void initialize() {
        System.out.println("AutoEngine.initialize");
    }

    public void destroy() {
        System.out.println("AutoEngine.destroy");
    }
}

Below is the Spring configuration file that where we register the bean. You’ll see in the configuration there are additional attributes that we add to the bean.

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

    <bean id="engine" class="org.kodejava.spring.core.AutoEngine" init-method="initialize" destroy-method="destroy" />

</beans>

Create a small program to execute our demo:

package org.kodejava.spring.core;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class InitDestroyDemo {
    public static void main(String[] args) {
        ConfigurableApplicationContext context =
                new ClassPathXmlApplicationContext("init-destroy.xml");

        AutoEngine engine = (AutoEngine) context.getBean("engine");

        // context.close will remove the bean from the container. 
        // This will call our bean destroy method.
        context.close();
    }
}

When you run the program it will print the following output:

AutoEngine.initialize
AutoEngine.destroy

The advantage of using this method to initialize or clean up the bean is that it does not mandate our bean to implement or extend any Spring API which will make our bean reusable on other container beside Spring.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I define bean scoping in Spring?

Bean scoping is how the bean is created and returned from the spring container to the bean requester. By default, the scope of all bean is singleton. The spring container will always return the same bean whenever this bean is required, for instance when in injected or call using the getBean() method from the application context.

There are five types of bean scope define in the Spring Container:

Scope Description
singleton Scope the bean definition to a single bean instance per Spring Container. This is the default scope when no scope is defined when creating a bean.
prototype Scope the bean to allow multiple times bean creation. This will create a new bean for each time the bean is required.
request Scope the bean definition to a single HTTP request. *
session Scope the bean definition to a single HTTP session. *
global-session Scope the bean definition to a global HTTP session. *

*) This is only valid when using the web-capable Spring context.

Let’s see the difference between Singleton and Prototype scope. First we’ll create our DummyService class.

package org.kodejava.spring.core;

public class DummyService {
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

Singleton Scope

By default, when no scope defined it will be a singleton.

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

    <bean id="service" class="org.kodejava.spring.core.DummyService" />

</beans>

Now create a program to run our example. First will run it using the singleton.xml as the configuration.

package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanScopeDemo {
    public static void main(String[] args) {
        try (var context = new ClassPathXmlApplicationContext("singleton.xml")) {
            DummyService serviceA = (DummyService) context.getBean("service");
            serviceA.setMessage("Hello From A");
            System.out.println("Message A = " + serviceA.getMessage());

            DummyService serviceB = (DummyService) context.getBean("service");
            System.out.println("Message B = " + serviceB.getMessage());
        }
    }
}

The output of the singleton configuration is:

Message A = Hello From A
Message B = Hello From A

The above output show that the message printed by the serviceB is the same as the serviceA. We don’t even set the message in the serviceB explicitly. It prints the same message because the getBean() method actually return the same bean both for serviceA and serviceB. This is the singleton scope.

Prototype Scope

To change the scope to prototype use the scope attribute in the bean element as shown 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.xsd">

    <bean id="service" class="org.kodejava.spring.core.DummyService" scope="prototype" />

</beans>
package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanScopePrototypeDemo {
    public static void main(String[] args) {
        try (var context = new ClassPathXmlApplicationContext("prototype.xml")) {
            DummyService serviceA = (DummyService) context.getBean("service");
            serviceA.setMessage("Hello From A");
            System.out.println("Message A = " + serviceA.getMessage());

            DummyService serviceB = (DummyService) context.getBean("service");
            System.out.println("Message B = " + serviceB.getMessage());
        }
    }
}

Now if you try to run the same program again but changing the configuration to prototype.xml you’ll get the following output printed:

Message A = Hello From A
Message B = null

The serviceB now print a different message. This is the effect of using the prototype scope. When we call the getBean() a new bean will be created per request.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I inject a bean through constructors?

The following example demonstrate how we can inject a bean through their constructors. We will create a couple interfaces and classes for this purpose. First we will create the Singer interface and the Instrument interface. The Singer interface define a single method call sing() that will enable the implementation to sing a song.

The second interface, Instrument also define a single method call play(). This method will allow the implementation to play some instrument. After defining our example interface we create an implementation for each of them. The class will be called the AnySinger and Piano.

Here are the code that we have to code so far:

package org.kodejava.spring.core;

public interface Singer {
    /**
     * Sing a song.
     */
    void sing();
}
package org.kodejava.spring.core;

public interface Instrument {
    /**
     * Play an instrument.
     */
    void play();
}
package org.kodejava.spring.core;

public class AnySinger implements Singer {
    private String song = "Nana nana nana";
    private Instrument instrument = null;

    public AnySinger() {
    }

    /**
     * A constructor to create singer to sing a specific song.
     *
     * @param song the song title to sing.
     */
    public AnySinger(String song) {
        this.song = song;
    }

    /**
     * A constructor to create singer to sing a song while playing
     * an instrument.
     *
     * @param song       the song title to sing.
     * @param instrument the instrument to play.
     */
    public AnySinger(String song, Instrument instrument) {
        this.song = song;
        this.instrument = instrument;
    }

    @Override
    public void sing() {
        System.out.println("Singing " + song);
        if (instrument != null) {
            instrument.play();
        }
    }
}
package org.kodejava.spring.core;

public class Piano implements Instrument {

    @Override
    public void play() {
        System.out.println("Playing the Piano");
    }
}

We have created the classes that we need for our program to work. The next step is to create our spring configuration file. This will configure our bean in the spring container and wire all the dependency required by the bean.

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

    <bean id="piano" class="org.kodejava.spring.core.Piano" />

    <bean id="singer" class="org.kodejava.spring.core.AnySinger">
        <constructor-arg value="Dust in The Wind" />
        <constructor-arg ref="piano" />
    </bean>

</beans>

In the spring configuration we declare two beans. The first bean is the piano bean, which is a type of instrument. The main object of our example is the singer bean. To create the singer we use a constructor injector to inject some values or object reference for the bean to use.

In the singer bean we use the &lt;constructor-arg/&gt; element to inject dependency for the object. The value attribute can be use for passing a string or other primitive value. To pass an object reference we need to use the ref attribute.

Finally, we’ll create a simple program to run our constructed spring application. The code will include the process of loading our spring container, obtaining the bean from the container. Let’s see our singer in action.

package org.kodejava.spring.core;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SingerDemo {
    public static void main(String[] args) {
        ConfigurableApplicationContext context =
                new ClassPathXmlApplicationContext("singer.xml");

        Singer singer = (Singer) context.getBean("singer");
        singer.sing();
        context.close();
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I declare a bean in Spring application?

In this example we will learn how to declare a bean in Spring Application. We are going to build a simple Maven project to demonstrate it. So let’s begin by setting up our Maven project.

Creating a Maven Project

Below is the directory structure of our Maven Project.

.
├─ pom.xml
└─ src
   └─ main
      ├─ java
      │  └─ org
      │     └─ kodejava
      │        └─ spring
      │           └─ core
      │              ├─ Hello.java
      │              ├─ HelloImpl.java
      │              └─ HelloWorldDemo.java
      └─ resources
         └─ spring.xml

Configuring Maven pom.xml File

We need to create a pom.xml file and add our project configuration and library dependency.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>kodejava-example</artifactId>
        <groupId>org.kodejava</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>kodejava-springframework-core</artifactId>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.3.23</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.3.23</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.3.23</version>
        </dependency>
    </dependencies>
</project>

Creating a Bean

Next we will create a simple bean called HelloImpl. This bean implements an interface called Hello with a single method sayHello() to be implemented. Here is the interface it’s implementation definition.

package org.kodejava.spring.core;

public interface Hello {
    void sayHello();
}
package org.kodejava.spring.core;

public class HelloImpl implements Hello {

    public void sayHello() {
        System.out.println("Hello World!");
    }
}

Register the Bean in Spring Configuration

After having the bean we need to create the Spring configuration, which is an xml file, and we named it spring.xml. The bean declared using the bean element in the configuration file. At minimum the declaration contains the bean’s id and it’s class.

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

    <bean id="hello" class="org.kodejava.spring.core.HelloImpl" />

</beans>

Use the Bean in Our Application

Now we have the bean declared in the Spring container. The next step show you how to get the bean from the container and use it in our program. There are many ways that can be used to load the Spring container. Here we will use the ClassPathXmlApplicationContext. This class load the configuration that found in the runtime classpath.

package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloWorldDemo {
    public static void main(String[] args) {
        String config = "spring.xml";
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);

        Hello hello = (Hello) context.getBean("hello");
        hello.sayHello();
        context.close();
    }
}

How do I list property names of a Bean?

package org.kodejava.bean;

import java.io.Serializable;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.beans.IntrospectionException;

public class Fruit implements Serializable {
    private Long id;
    private String name;
    private String latinName;
    private double price;

    public Fruit() {
    }

    public static void main(String[] args) {
        try {
            BeanInfo bi = Introspector.getBeanInfo(Fruit.class);
            PropertyDescriptor[] pds = bi.getPropertyDescriptors();

            for (PropertyDescriptor pd : pds) {
                String propertyName = pd.getName();

                System.out.println("propertyName = " + propertyName);
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLatinName() {
        return latinName;
    }

    public void setLatinName(String latinName) {
        this.latinName = latinName;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

The output of the code snippet above are:

propertyName = class
propertyName = id
propertyName = latinName
propertyName = name
propertyName = price