riven

Riven

Riven

Spring Framework in java with example

The Spring Framework is an open-source application framework for Java that provides comprehensive infrastructure support for developing Java applications. It was created to simplify Java development and promote good design practices. Since its initial release in 2003, it has evolved into a robust platform that supports various programming paradigms, including object-oriented, aspect-oriented, and reactive programming.

Core Concepts of Spring

  1. Inversion of Control (IoC):

    • Spring uses IoC to manage the dependencies between objects, promoting loose coupling. Instead of creating dependencies manually, the framework provides a container that takes care of instantiating and managing these objects.
  2. Dependency Injection (DI):

    • DI is a specific implementation of IoC. It allows objects to receive their dependencies from an external source rather than creating them internally. This can be done through constructor injection, setter injection, or method injection.
  3. Aspect-Oriented Programming (AOP):

    • AOP complements OOP by allowing separation of cross-cutting concerns (e.g., logging, security). Spring AOP provides support for aspect-oriented programming through proxies.
  4. Spring Container:

    • The Spring Container is the core of the Spring Framework. It is responsible for managing the lifecycle of beans, which are objects created and managed by the Spring IoC container.
  5. Spring MVC:

    • Spring MVC is a module within the Spring Framework that provides model-view-controller architecture for web applications. It enables developers to build flexible and loosely coupled web applications.
  6. Spring Boot:

    • An extension of the Spring Framework, Spring Boot simplifies the setup and development of new Spring applications. It uses convention over configuration and provides embedded web servers, making it easy to get started with Spring.

Spring Framework Architecture

The architecture of the Spring Framework is modular, consisting of several layers:

  1. Core Container:

    • Beans: This module provides the configuration and management of beans.
    • Core: This is the foundational layer of the Spring Framework, providing IoC and DI functionalities.
    • Context: The ApplicationContext is a central interface to the Spring IoC container, providing additional functionalities like event propagation and resource loading.
    • Expression Language (SpEL): This module allows querying and manipulation of objects at runtime.
  2. AOP Module:

    • Provides aspect-oriented programming capabilities, allowing developers to define and apply aspects.
  3. Data Access/Integration:

    • JDBC: Simplifies JDBC operations and exception handling.
    • ORM: Provides integration with Object-Relational Mapping frameworks like Hibernate and JPA.
    • JMS: Supports Java Messaging Service for messaging solutions.
  4. Web Module:

    • Web: Provides basic web-oriented integration features.
    • Web MVC: Supports building web applications using the MVC pattern.
  5. Security:

    • Spring Security provides comprehensive security services for Java applications, including authentication and authorization.

Setting Up a Spring Application

Prerequisites

  • Java Development Kit (JDK): Make sure you have JDK 8 or later installed.
  • Maven: We’ll use Maven for dependency management.

Maven Project Setup

Create a new Maven project with the following structure:

				
					spring-example/
|-- pom.xml
|-- src/
    |-- main/
        |-- java/
        |   `-- com/example/spring/
        |       |-- config/
        |       |   `-- AppConfig.java
        |       |-- controller/
        |       |   `-- HelloController.java
        |       `-- model/
        |           `-- Greeting.java
        |-- resources/
            `-- application.properties
				
			

pom.xml

Here’s a basic pom.xml file with Spring dependencies:

				
					<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">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>spring-example</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.9</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.32</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.32</version>
        </dependency>
    </dependencies>
</project>
				
			

Creating the Application Configuration

AppConfig.java

This is the configuration class where we define our beans.

				
					package com.example.spring.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.example.spring")
public class AppConfig {
}
				
			

Creating the Model

Greeting.java

This class represents the data model.

				
					package com.example.spring.model;

public class Greeting {
    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}
				
			

Creating the Controller

HelloController.java

This controller handles web requests

				
					package com.example.spring.controller;

import com.example.spring.model.Greeting;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

@RestController
public class HelloController {

    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format("Hello, %s!", name));
    }
}
				
			

Setting Up the Web Application

You need to configure a web application initializer to bootstrap the Spring context.

WebInitializer.java

				
					package com.example.spring;

import com.example.spring.config.AppConfig;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class WebInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(AppConfig.class);
        context.setServletContext(servletContext);

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
}
				
			

Running the Application

To run the application, you can deploy it on a servlet container like Apache Tomcat or use Spring Boot to run it as a standalone application.

Using Spring Boot

If you’re using Spring Boot, the main method in the application can be defined as follows:

				
					package com.example.spring;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringExampleApplication.class, args);
    }
}
				
			

Testing the Application

After starting the application, you can test it by navigating to:

				
					http://localhost:8080/greeting?name=John
				
			

You should see a JSON response like this:

				
					{
    "id": 1,
    "content": "Hello, John!"
}
				
			

Related post

TreeMap in Java with example
what is Treemap in java with example in Java, a TreeMap is part of the Java Collections Framework and...
Single inheritance in java
Single inheritance in java Inheritance is one of the core concepts of object-oriented programming (OOP)....
Encapsulation in java
Java Encapsulation Encapsulation is one of the four fundamental Object-Oriented Programming (OOP) concepts,...
IOC container in spring
What is  IoC Container in spring? The Spring IoC container is responsible for managing the complete...
Java collections
Java Collections Framework The Java Collections Framework (JCF) is a unified architecture that provides...
File handling in java
File handling in java with example File handling in Java refers to the process of reading from and writing...
Else if statement
Java else if statement The else if statement in Java is a powerful construct that allows for more complex...
AWT panel in java
What is AWT Panel in Java? A Panel in Java refers to an instance of the JPanel class, which is part of...
Multiple inheritance in java
Multiple inheritance in java Multiple inheritance is a feature in object-oriented programming where a...
Java for loop with example
Java for loop with example The for loop is one of the most commonly used control flow statements in Java,...