Java standalone application in Spring with configuration file

February 15, 2018

In this tutorial, I am going to create simple Java standalone application in Spring Framework. For the dependency injection I am going to use XML configuration file

First I will create the Java Standalone Application
File > New Project

Next I will create a class Car under com.kayak package

package com.kayak;

public class Car {

 
    private String name;

    public Car() {

    }

    public String getName() {
        return name;
    }

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

    
}

This a simple bean to represent Car. Now I will add bean.xml file to your class path and add following code to it





    
        
    
  


You can see that ID given to the com.kayak.Car class is car . So this bean has name property and it has the value filed also

To configure setter injection by using XML configuration, you need to specify tags under the tag for each into which you want to inject a dependency.

Now, we we need to load this bean.xml to application context and get the bean from the context

So in your file you can add the following code

package springstrat;

import com.kayak.Car;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class SpringStrat {


    public static void main(String[] args) {
        
        ApplicationContext ctx = new  ClassPathXmlApplicationContext("bean.xml");
        Car car=(Car)ctx.getBean("car");
        System.out.println(car.getName());
        
    }
    
}

When you run this application you will get the output as Audi .