Spring 4 xml configuration example

The Spring 4 xml configuration example shows you how to use Spring XML Based Configuration via a simple Spring application. This application involves a service which will display a simple message to the console and we configure this application with Spring XML. Then, we bootstrap the Spring context(ApplicationContext) using the ClassPathXmlApplicationContext.

Maven Dependencies
To build this application, we need to add the spring-core and spring-context dependencies to the classpath.

Create Spring Service
We create the HelloService class is used to demonstrate how to use spring XML based configuration.

Spring XML Based Configuration

A spring configuration is a xml file which consists of at least one or more than one bean definition. These beans are registered with Spring container using the element inside a top-level element. These bean definitions correspond to the java objects that is used in our application. In this example we create a bean of type HelloService. We register this bean with Spring container by creating a element and adding the fully qualified class name of the bean to the class attribute. Let see the detail below:

Demo Spring ApplicationContext

We start the ApplicationContext using the ClassPathXmlApplicationContext. We pass the location of spring-config.xml file(Spring XML Based Configuration) using an array of strings. Then, we use the getBean method with the paramatter class name to get the spring managed bean. Finally we can call the makeHello method of the HelloService.

Run the main class above, the output will be printed like below

References
ClassPathXmlApplicationContext JavaDoc

Download complete source code, please click link below

spring-4-xml-configuration-example.zip (20 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons