Spring Introduction

Understanding the foundation of Java enterprise development

🌱 What is Spring Framework?

Spring is a powerful Java framework that simplifies enterprise application development. It provides comprehensive infrastructure support, dependency injection, and helps create robust, maintainable applications with less boilerplate code.


// Simple Spring Bean example
@Component
public class HelloService {
    public String sayHello() {
        return "Hello from Spring!";
    }
}
                                    

Key Spring Concepts

💉

Dependency Injection

Spring manages object dependencies automatically

@Autowired
private UserService userService;
🏗️

IoC Container

Inversion of Control manages object lifecycle

@Component
public class MyService { }
🎯

AOP

Aspect-Oriented Programming for cross-cutting concerns

@Aspect
@Component
public class LoggingAspect { }
🔧

Configuration

Flexible configuration options

@Configuration
public class AppConfig { }

🔹 Basic Spring Application

Here's a simple Spring application structure:

// Main Application Class
@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

// Service Component
@Service
public class UserService {
    public String getUser() {
        return "John Doe";
    }
}

// Controller
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    
    @GetMapping("/user")
    public String getUser() {
        return userService.getUser();
    }
}

Output:

GET /user → "John Doe"

🔹 Spring Modules

Spring Framework consists of several modules:

  • Spring Core: Dependency Injection and IoC
  • Spring MVC: Web application development
  • Spring Data: Database access and ORM
  • Spring Security: Authentication and authorization
  • Spring Boot: Auto-configuration and rapid development

🔹 Why Use Spring?

Spring provides many benefits for Java developers:

// Without Spring - Manual dependency management
public class OrderService {
    private PaymentService paymentService = new PaymentService();
    private EmailService emailService = new EmailService();
}

// With Spring - Automatic dependency injection
@Service
public class OrderService {
    @Autowired
    private PaymentService paymentService;
    
    @Autowired
    private EmailService emailService;
}

Spring Benefits:

  • Reduces boilerplate code
  • Easier testing with dependency injection
  • Modular architecture
  • Large ecosystem and community

🧠 Test Your Knowledge

What is the main purpose of Spring's Dependency Injection?