The Wayback Machine - https://web.archive.org/web/20240528092148/https://www.geeksforgeeks.org/spring-application-without-any-xml-configuration/
Open In App

Spring Application Without Any .xml Configuration

Last Updated : 27 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Spring MVC Application Without the web.xml File, we have eliminated the web.xml file, but we have left with the spring config XML file that is this file “application-config.xml“. So here, we are going to see how to eliminate the spring config XML file and build a spring application without any .xml configuration.  

Implementation: Project 

Let us demonstrate Spring Application Without Any .xml Configuration stepwise that is as follows: 

Step 1: Set up the project

Note: We are going to use Spring Tool Suite 4 IDE for this project. Please for refer prior  to install STS on your local machine How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE? 

Go to your STS IDE then create a new maven project, File > New > Maven Project, and choose the following archetype as shown in the below image as follows:  

 

Step 2: Adding Some Maven Dependencies

Add the following maven dependencies and plugin to your pom.xml file. 

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.18</version>
</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>

<!-- plugin -->
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
</build>

Below is the complete code for the pom.xml file after adding these dependencies.

File: pom.xml 

XML




    <modelVersion>4.0.0</modelVersion>
    <groupId>com.geeksforgeeks</groupId>
    <artifactId>spring-calculator</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-calculator Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>spring-calculator</finalName>
        <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
    </build>
</project>


Step 3: Building Spring Application Without Any .xml Configuration

Before moving into the coding part let’s have a look at the file structure in the below image. As you can see in the file structure we have no file with .xml configuration. 

 

So at first create an src/main/java folder and inside this folder create a class named CalculatorApplicationInitializer and put it inside the com.geeksforgeeks.calculator.config package and implement the WebApplicationInitializer interface. Refer to the below image.

 

Now we have to create the spring config class and register the class with our WebApplicationContext. So go to the src/main/java folder and inside this folder create a class named CalculatorAppConfig and put it inside the com.geeksforgeeks.calculator.config package. 

File: CalculatorAppConfig.java file

Java




// Java Illusion for CalculatorAppConfig Class
 
package com.geeksforgeeks.calculator.config;
 
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
// Class
@Configuration
@ComponentScan(basePackages = "com.geeksforgeeks.calculator.controllers")
public class CalculatorAppConfig {
 
}


We have used the @Configuration and @ComponentScan annotation in the above class. Overall we can say this class is the replacement of the following .xml file. 

XML




<?xml version="1.0" encoding="UTF-8"?>
   
  <context:component-scan base-package="com.geeksforgeeks.calculator.controllers"></context:component-scan>
         
</beans>


File: CalculatorApplicationInitializer.java

Java




// Java Program to Illustrate
// CalculatorApplicationInitializer Class
 
package com.geeksforgeeks.calculator.config;
 
// Importing required classes
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
 
// Class
// Implementing WebApplicationInitializer interface
public class CalculatorApplicationInitializer
    implements WebApplicationInitializer {
 
    // Method
    public void onStartup(ServletContext servletContext)
        throws ServletException
    {
 
        AnnotationConfigWebApplicationContext
            webApplicationContext
            = new AnnotationConfigWebApplicationContext();
 
        // Registering the spring config class
        webApplicationContext.register(
            CalculatorAppConfig.class);
 
        // Creating a dispatcher servlet object
        DispatcherServlet dispatcherServlet
            = new DispatcherServlet(webApplicationContext);
 
        // Registering Dispatcher Servlet
      // with Servlet Context
        ServletRegistration
            .Dynamic myCustomDispatcherServlet
            = servletContext.addServlet(
                "myDispatcherServlet", dispatcherServlet);
 
        // Setting load on startup
        myCustomDispatcherServlet.setLoadOnStartup(1);
 
        // Adding mapping URL
        myCustomDispatcherServlet.addMapping("/gfg.com/*");
    }
}


Step 4: Create Controller and Test The Application

Go to the src/main/java folder and inside this folder create a class named GfgController and put it inside the ‘com.geeksforgeeks.calculator.controllers’ package. Below is the code for the GfgController.java file.

File: GfgController.java

Java




// Java Program to Illustrate GfgController Class
 
package com.geeksforgeeks.calculator.controllers;
 
// Importing required classes
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
// Class
@Controller
public class GfgController {
 
    // Testor method
    @RequestMapping("/welcome")
    @ResponseBody
    public String helloGfg()
    {
        return "Welcome to GeeksforGeeks!";
    }
}


Step 5: Run The Application

Now run your spring MVC application and hit the following URL

http://localhost:8080/spring-calculator/gfg.com/welcome

And we can see the output as shown in the below image as depicted below as follows: 

 



Previous Article
Next Article

Similar Reads

Spring MVC Application Without web.xml File
Spring MVC framework enables separation of modules namely Model, View, and Controller, and seamlessly handles the application integration. This enables the developer to create complex applications also using plain java classes. Here we will be creating and running Your First Spring MVC Application, whenever we are Configuring Dispatcher Servlet we
4 min read
Spring - AOP AspectJ Xml Configuration
Spring allows you to specify aspects, recommendations, and pointcuts in an XML file. Annotations were used in the aop examples on the preceding page. The XML configuration file will now show us the same samples. Let's look at the XML components that describe advice. aop:before: It's used before the real business logic procedure is called.aop:after:
7 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code &lt;?xml version=&quot;1.0&quot; encoding=
4 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
How to Run Your First Spring Boot Application in Spring Tool Suite?
Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for the favorite coding environment. Largely rebuilt
3 min read
Configuring Multiple Spring Batch Jobs in a Spring Boot Application
Spring Batch serves as a robust framework within the Spring ecosystem, specifically tailored for managing batch processing tasks efficiently. It's designed to tackle big data jobs efficiently and comes with handy tools to make batch application development a breeze. In the context of a Spring Boot application, setting up multiple Spring Batch jobs
10 min read
Spring Boot - application.yml/application.yaml File
Spring is widely used for creating scalable applications. For web applications Spring provides. In Spring Boot, whenever we create a new Spring Boot Application in spring starter, or inside an IDE (Eclipse or STS) a file is located inside the src/main/resources folder named as application.properties file which is shown in the below media: So in a s
4 min read
Spring MVC using Java based configuration
Prerequisites: MVC Design Pattern, Spring MVC with JSP ViewSpring MVC framework enables separation of modules namely Model, View and Controller and seamlessly handles the application integration. This enables the developer to create complex applications also using plain java classes. The model object can be passed between view and controller using
5 min read
Spring Boot - Create a Custom Auto-Configuration
Usually, we might be taking a maven project or grade project for Spring Boot related projects. We will be adding the dependencies in pom.xml (in case of a maven project). In a spring application, Spring Boot auto-configuration helps to automatically configure by checking with the jar dependencies that we have added. For example, though no beans are
4 min read
Article Tags :
Practice Tags :