DEV Community

Galisetty Priyatham
Galisetty Priyatham

Posted on

A Guide to the Spring Framework with Examples

1. Introduction to Spring Framework

The Spring Framework is a powerful platform for developing Java applications. It started in 2002 and helps developers build secure, efficient, and maintainable software. Think of Spring as a toolkit that organizes and wires up all the parts of a Java application so you don’t have to do it manually.
At the heart of Spring is Inversion of Control (IoC) and Dependency Injection (DI)—fancy terms that simply mean Spring creates and manages the objects your app needs and connects them together.


2. The Problem Spring Solves

Traditional Java EE (Before Spring):
• Lots of repetitive code.
• Hard to test small parts without setting up everything.
• Complex setup with XML files and interfaces.

Spring’s Solution:
Less code: Write only what’s necessary.
Better testability: Easily test parts of your app without starting the whole app.
Simpler wiring: Let Spring create and connect the objects.


3. Spring Framework Architecture vs Legacy Java EE

Legacy Java EE Architecture:

Image description

• Tightly coupled components
• Deployment descriptors (XML) needed for almost everything
• Testing required full application server (like JBoss or WebLogic)

Spring Architecture:

Image description

• Loose coupling using IoC/DI
• Annotations replace XML
• Easy unit and integration testing without full container

Visual Comparison Diagram

Image description

Analogy:

Imagine a company:
• In Java EE, every department (EJB, DAO) manages its own setup—forms, meetings, permissions. A huge overhead for small changes.
• In Spring, there’s an office manager (Spring Container) that wires up teams, resources, and schedules, so departments only focus on their job.


4. Core Concepts with Examples

a) Dependency Injection (DI)
Imagine you’re making a car, and the car needs an engine. Instead of making the engine inside the Car class, Spring gives the Car class an already-built engine.

public class Engine {
    public String start() {
        return "Engine started";
    }
}

public class Car {
    private Engine engine;

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

    public void drive() {
        System.out.println(engine.start());
    }
}
Enter fullscreen mode Exit fullscreen mode

With Spring:

@Configuration
public class AppConfig {
    @Bean
    public Engine engine() {
        return new Engine();
    }

    @Bean
    public Car car() {
        return new Car(engine());
    }
}
Enter fullscreen mode Exit fullscreen mode

b) Bean Scopes
• singleton: One object per Spring container (default).
• prototype: A new object every time you ask for it.

@Component
@Scope("prototype")
public class Toy {
    public Toy() {
        System.out.println("New Toy created!");
    }
}
Enter fullscreen mode Exit fullscreen mode

c) Autowiring
Let Spring inject dependencies automatically.

@Component
public class Engine {
    public String start() {
        return "Engine running";
    }
}

@Component
public class Car {
    @Autowired
    private Engine engine;

    public void drive() {
        System.out.println(engine.start());
    }
}
Enter fullscreen mode Exit fullscreen mode

5. Enterprise Services in Spring

a) Spring MVC (Web Development)

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }
}

Enter fullscreen mode Exit fullscreen mode

b) Data Access with Spring Data JPA

@Entity
public class User {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
}

public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByName(String name);
}
Enter fullscreen mode Exit fullscreen mode

c) Transactions

@Service
public class BankService {
    @Autowired
    private AccountRepository accountRepo;

    @Transactional
    public void transferMoney(Long fromId, Long toId, double amount) {
        Account from = accountRepo.findById(fromId).get();
        Account to = accountRepo.findById(toId).get();
        from.setBalance(from.getBalance() - amount);
        to.setBalance(to.getBalance() + amount);
    }
}
Enter fullscreen mode Exit fullscreen mode

d) Messaging (JMS)

@Component
public class MyReceiver {
    @JmsListener(destination = "myQueue")
    public void receiveMessage(String msg) {
        System.out.println("Received: " + msg);
    }
}
Enter fullscreen mode Exit fullscreen mode

6. What is Spring Boot?

Spring Boot simplifies everything.
• Adds built-in servers like Tomcat.
• No need to configure everything manually.
• Provides “starters” to get going quickly.

@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}
Enter fullscreen mode Exit fullscreen mode

application.properties
server.port=8081
spring.datasource.url=jdbc:h2:mem:test


7. Different Flavors of Spring

Image description

@EnableDiscoveryClient
@SpringBootApplication
public class MyMicroserviceApp {
    public static void main(String[] args) {
        SpringApplication.run(MyMicroserviceApp.class, args);
    }
}
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .anyRequest().authenticated()
            .and().formLogin();
    }
}

Enter fullscreen mode Exit fullscreen mode

8. Other Key Spring Projects

Spring Security: Secures your app with login, roles, and more.
Spring Cloud: Helps in building scalable microservices (e.g., Netflix Eureka, Ribbon).
Spring Batch: Supports batch processing of large data.


9. Spring Cheat Sheet Summary

Image description


Spring makes Java development modern, testable, and easier to manage. Spring Boot takes this one step further by reducing configuration and giving you production-ready defaults. Different flavors of Spring make it versatile enough to handle small apps, large enterprise systems, microservices, and everything in between.
In short, Spring helps developers focus on building features instead of spending time on repetitive configurations and setups. It’s like having a well-organized kitchen where every tool is ready for you to cook a great dish—fast, efficient, and hassle-free.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.