Wednesday, 26 February 2025

Spring Modules

     Spring Framework consists of several core modules that provide different functionalities for building Java applications. Below is a breakdown of major Spring modules along with relevant code examples.

1. Spring Core Module

Spring Core Module provides the fundamental features of the Spring Framework, including Dependency Injection (DI) and Inversion of Control (IoC).

Example: Dependency Injection using XML and Annotations

applicationContext.xml

<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.xsd">

    <bean id="car" class="com.example.Car">
        <property name="engine" ref="engine"/>
    </bean>

    <bean id="engine" class="com.example.Engine">
        <property name="type" value="V8"/>
    </bean>
</beans>

Java Configuration:

@Configuration
@ComponentScan("com.example")
public class AppConfig {

    @Bean
    public Engine engine() {
        return new Engine("V8");
    }

    @Bean
    public Car car() {
        return new Car(engine());
    }
}

Car.java

@Component
public class Car {
    private Engine engine;

    @Autowired
    public Car(Engine engine) {
        this.engine = engine;
    }

    public void start() {
        System.out.println("Car started with " + engine.getType());
    }
}

2. Spring AOP (Aspect-Oriented Programming)

Spring AOP module helps implement cross-cutting concerns like logging, security, and transaction management.

Example: Logging Aspect

@Aspect
@Component public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void logBeforeMethodExecution(JoinPoint joinPoint) { System.out.println("Executing: " + joinPoint.getSignature().getName()); } }

3. Spring JDBC Module

Spring JDBC module provides a way to interact with relational databases.

Example: JDBC Template

@Repository public class EmployeeDAO { @Autowired private JdbcTemplate jdbcTemplate; public void insert(Employee emp) { String sql = "INSERT INTO employees (id, name, salary) VALUES (?, ?, ?)"; jdbcTemplate.update(sql, emp.getId(), emp.getName(), emp.getSalary()); } }

4. Spring ORM Module

Spring ORM module integrates with ORM frameworks like Hibernate.

Example: Hibernate Integration

@Entity
@Table(name = "employees") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private double salary; }
EmployeeRepository.java
 
@Repository
public class EmployeeRepository {
    @Autowired
    private EntityManager entityManager;

    public void save(Employee emp) {
        entityManager.persist(emp);
    }
}

5. Spring MVC Module

Spring MVC is used to build web applications.

Example: REST Controller

@RestController
@RequestMapping("/employees")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/{id}")
    public Employee getEmployee(@PathVariable Long id) {
        return employeeService.getEmployeeById(id);
    }
}

6. Spring Security

Spring Security provides authentication and authorization.

Example: Security Configuration

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .requestMatchers("/user/**").authenticated()
                .anyRequest().permitAll()
            )
            .formLogin()
            .and()
            .logout();
        return http.build();
    }
}

7. Spring Boot Module

Spring Boot simplifies application development with auto-configuration.

Example: Main Application

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

8. Spring Cloud (Microservices)

Spring Cloud helps in building microservices architectures.

Example: Eureka Service Discovery

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

Below are some notable projects and resources that, collectively, cover these modules:

1. Microservice Architecture with Spring Cloud

This project demonstrates a microservices architecture using Spring Cloud and various Spring modules.

  • Repository: Microservice Architecture

  • Highlights:

    • Spring Boot: Simplifies application setup.
    • Spring Cloud: Manages configuration, service discovery, and routing.
    • Spring Security: Implements authentication and authorization.
    • Spring Data JPA (ORM): Manages data persistence.
    • Spring MVC: Handles web requests.
    • Spring AOP: Manages cross-cutting concerns.

While this project primarily uses MySQL, adapting it to MSSQL involves modifying the database configuration.


2. Spring Boot JdbcTemplate with SQL Server

This project focuses on integrating Spring Boot with MSSQL using JdbcTemplate.

  • Repository: Spring Boot JdbcTemplate Example with SQL Server

  • Highlights:

    • Spring Boot: Simplifies application setup.
    • Spring JDBC (JdbcTemplate): Facilitates database interactions.
    • MSSQL Integration: Demonstrates configuration for MSSQL connectivity.

This project provides a foundation for MSSQL integration, which can be extended to include other modules like Security, AOP, and Cloud.


3. Microservices with Spring Masterclass

This repository offers a comprehensive guide to building microservices with Spring Boot and Spring Cloud.

  • Repository: Microservices with Spring Masterclass

  • Highlights:

    • Spring Boot: Simplifies microservice development.
    • Spring Cloud: Manages service discovery, configuration, and routing.
    • Spring Security: Implements security measures.
    • Spring Data JDBC: Manages data persistence.
    • Spring WebFlux (MVC): Handles reactive web requests.

The project uses PostgreSQL for data storage, but the configuration can be adapted for MSSQL.


4. Spring Boot Complete

This repository encompasses a wide range of Spring Boot projects, covering various modules and configurations.

  • Repository: Spring Boot Complete

  • Highlights:

    • Spring Core: Demonstrates dependency injection and IoC.
    • Spring MVC: Showcases web application development.
    • Spring Security: Implements security features.
    • Spring Data JPA (ORM): Manages data persistence.
    • Spring Boot: Provides various configurations and setups.

While the projects use different databases, they can be reconfigured to work with MSSQL.


Combining Insights:

By studying these projects, you can gain insights into integrating various Spring modules. To build a comprehensive application with MSSQL, consider the following steps:

  1. Set Up MSSQL Database:

    • Deploy an MSSQL instance locally or in the cloud.
    • Create the necessary databases and tables.
  2. Configure Spring Data Source:

    • In your application.properties or application.yml, set the datasource properties for MSSQL:

      properties
      spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=your_db_name spring.datasource.username=your_username spring.datasource.password=your_password spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
  3. Integrate Spring Modules:

    • Core: Set up dependency injection and IoC containers.
    • Security: Implement authentication and authorization using Spring Security.
    • AOP: Use Aspect-Oriented Programming for cross-cutting concerns like logging.
    • JDBC/ORM: Utilize Spring Data JPA or JdbcTemplate for database interactions.
    • MVC: Develop RESTful APIs or web applications using Spring MVC.
    • Boot: Leverage Spring Boot for application setup and configuration.
    • Cloud: Incorporate Spring Cloud components for microservices architecture, such as service discovery and configuration management.
  4. Testing and Deployment:

    • Write unit and integration tests to ensure application stability.
    • Use Docker or cloud platforms to deploy your application.