WHAT'S NEW?
Loading...

HelloWorld Spring Application

Three files as my source files:
1. HelloWorld Class with a String as private field with getters and setters functions.
2. MainApplication class with main method that instantiates an object of HellowWorld class.
3. A Configuration File with configuration metadata.

HelloWorld.java
package com.spring.one;
public class HelloWorld {
    private String message;

    public String getMessage() {
        return message;
    }

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

Beans.xml
<?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">

   <bean id="helloWorld" class="com.spring.one.HelloWorld">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>


MainApplication.java
package com.spring.one;

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

public class MainApp {
   
    public static void main(String[] args){
        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
        String str = obj.getMessage();
        System.out.println(str);
    }
}


What I do is: Define a HelloWorld Class. Define a MainApplication Class. From MainApplication class's main method, I instantiate a context object of class  ApplicationContext defined in spring framework. The configuration file is passed as an argument to this object. The configuration file assigns an id to our class HelloWorld. And its attributes or fields are defined as properties of the Beans object.


On Compiling, this program gives an output of "Hello World!" which is the value of property named "message" in the configuration file. There's type casting of Bean Object to object of HelloWorld class.

There's no call to setMessage() method of HelloWorld Class. But how the string value is set to "Hello World!"? Need to find. During the initialization of bean, MessageSourceAware's setMessageSource() method is executed and this is done as part of standard bean cycle. More details here.

0 comments:

Post a Comment