Spring Framework Basics
The Spring Framework is a Java library that creates your application's objects and connects them for you. Instead of writing new everywhere, you describe which objects exist and what they need, and Spring's IoC container builds and wires them. These Spring Framework basics, dependency injection, beans and the application context, are the foundation of Spring Boot, Spring MVC and Spring Data.
This lesson uses plain Spring Framework 7.0 (no Spring Boot yet) so you can see exactly what the container does. Spring Framework 7 requires Java 17 or newer and uses the jakarta.* namespace.
Spring Framework Basics: Key Terms
| Term | Meaning |
|---|---|
| Bean | An object created and managed by Spring |
| IoC container | The part of Spring that creates beans and controls their lifecycle ("Inversion of Control") |
ApplicationContext | The container you use in code; holds all beans |
| Dependency injection (DI) | Spring passes a bean the other beans it needs, usually through its constructor |
| Configuration | Instructions telling Spring which beans to create (@Configuration, @Bean, @Component) |
| Scope | How many instances of a bean exist (one shared, or a new one each time) |
How it works:
- Your classes stay plain Java. They declare what they need in their constructor, and Spring decides where those objects come from.
- Because classes no longer create their own dependencies, you can swap an implementation (email to SMS, real database to test data) by changing configuration instead of code.
Add Spring to a Maven Project
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>7.0.10</version>
</dependency>
</dependencies>
# Run any example class from the project folder
mvn -q compile exec:java -Dexec.mainClass=com.gocourse.spring.ConfigDemo
How it works:
spring-contextbrings in the core container (spring-core,spring-beans,spring-aop,spring-expression). That is all a plain Spring application needs.- The Create a Maven Project lesson shows how to set up the
pom.xmland folders.
The Problem Spring Solves: Manual Wiring
Start with three plain classes used throughout the lesson.
// src/main/java/com/gocourse/spring/model/Notifier.java
package com.gocourse.spring.model;
public interface Notifier {
void send(String to, String message);
}
// src/main/java/com/gocourse/spring/model/EmailNotifier.java
package com.gocourse.spring.model;
public class EmailNotifier implements Notifier {
@Override
public void send(String to, String message) {
System.out.println("EMAIL to " + to + ": " + message);
}
}
// src/main/java/com/gocourse/spring/model/EnrollmentService.java
package com.gocourse.spring.model;
public class EnrollmentService {
private final Notifier notifier;
public EnrollmentService(Notifier notifier) { // the dependency arrives from outside
this.notifier = notifier;
}
public void enroll(String student, String course) {
notifier.send(student, "You are enrolled in " + course);
}
}
package com.gocourse.spring;
import com.gocourse.spring.model.EmailNotifier;
import com.gocourse.spring.model.EnrollmentService;
import com.gocourse.spring.model.Notifier;
public class ManualWiringDemo {
public static void main(String[] args) {
Notifier notifier = new EmailNotifier(); // create
EnrollmentService service = new EnrollmentService(notifier); // wire
service.enroll("asha@example.com", "Java");
}
}
Output:
EMAIL to asha@example.com: You are enrolled in Java
How it works:
EnrollmentServicealready follows good design: it receives itsNotifierthrough the constructor instead of creating one.- But
mainmust still create every object in the right order. With 50 services, each needing several others, this wiring code becomes long and fragile. Spring takes over exactly this job.
Define Beans With @Configuration and @Bean
A @Configuration class contains @Bean methods. Each method returns one object that Spring manages.
package com.gocourse.spring;
import com.gocourse.spring.model.EmailNotifier;
import com.gocourse.spring.model.EnrollmentService;
import com.gocourse.spring.model.Notifier;
import java.util.Arrays;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class ConfigDemo {
@Configuration
static class AppConfig {
@Bean
Notifier notifier() {
return new EmailNotifier();
}
@Bean
EnrollmentService enrollmentService(Notifier notifier) { // Spring passes the notifier bean
return new EnrollmentService(notifier);
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) {
EnrollmentService service = context.getBean(EnrollmentService.class);
service.enroll("ravi@example.com", "Go");
EnrollmentService again = context.getBean(EnrollmentService.class);
System.out.println("Same instance? " + (service == again));
System.out.println("Notifier beans: " + Arrays.toString(context.getBeanNamesForType(Notifier.class)));
}
}
}
Output:
EMAIL to ravi@example.com: You are enrolled in Go
Same instance? true
Notifier beans: [notifier]
How it works:
AnnotationConfigApplicationContextreadsAppConfig, calls each@Beanmethod and stores the results. The method name becomes the bean name (notifier).- The
enrollmentServicemethod declares aNotifierparameter, and Spring fills it with thenotifierbean. That is dependency injection. - Beans are singletons by default:
getBeanreturns the same object every time. try-with-resources closes the context at the end, which also shuts down every bean cleanly.
Component Scanning and Constructor Injection
Writing a @Bean method for every class gets repetitive. With component scanning, Spring finds classes marked with a stereotype annotation and creates them automatically.
| Annotation | Use it for |
|---|---|
@Component | Any general bean |
@Service | Business logic classes |
@Repository | Data access classes (also translates database exceptions) |
@Controller | Web controllers (Spring MVC) |
@Configuration | Classes that contain @Bean methods |
// src/main/java/com/gocourse/spring/shop/CourseCatalog.java
package com.gocourse.spring.shop;
import java.util.Map;
import org.springframework.stereotype.Repository;
@Repository
public class CourseCatalog {
private final Map<String, Integer> fees = Map.of("java", 4999, "go", 2999, "python", 3999);
public int feeFor(String courseCode) {
Integer fee = fees.get(courseCode);
if (fee == null) throw new IllegalArgumentException("Unknown course: " + courseCode);
return fee;
}
}
// src/main/java/com/gocourse/spring/shop/PriceCalculator.java
package com.gocourse.spring.shop;
import org.springframework.stereotype.Component;
@Component
public class PriceCalculator {
public long withGst(int fee) {
return Math.round(fee * 1.18);
}
}
// src/main/java/com/gocourse/spring/shop/CheckoutService.java
package com.gocourse.spring.shop;
import org.springframework.stereotype.Service;
@Service
public class CheckoutService {
private final CourseCatalog catalog;
private final PriceCalculator calculator;
// One constructor: Spring uses it automatically, no @Autowired needed
public CheckoutService(CourseCatalog catalog, PriceCalculator calculator) {
this.catalog = catalog;
this.calculator = calculator;
}
public String quote(String courseCode) {
int fee = catalog.feeFor(courseCode);
return courseCode + ": fee " + fee + ", with GST " + calculator.withGst(fee);
}
}
// src/main/java/com/gocourse/spring/shop/ShopApp.java
package com.gocourse.spring.shop;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan // scans this package and its sub-packages
public class ShopApp {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(ShopApp.class)) {
CheckoutService checkout = context.getBean(CheckoutService.class);
System.out.println(checkout.quote("java"));
System.out.println(checkout.quote("go"));
System.out.println("Has checkoutService? " + context.containsBean("checkoutService"));
System.out.println("Has priceCalculator? " + context.containsBean("priceCalculator"));
}
}
}
Output:
java: fee 4999, with GST 5899
go: fee 2999, with GST 3539
Has checkoutService? true
Has priceCalculator? true
How it works:
@ComponentScanwith no package scans the package ofShopApp(com.gocourse.spring.shop) and below, and registersCourseCatalog,PriceCalculatorandCheckoutService.- Bean names come from the class name with a lowercase first letter:
checkoutService,priceCalculator. Pass a name to the annotation, such as@Service("checkout"), to choose your own. - Constructor injection is the recommended style. Fields can be
final, the class cannot exist without its dependencies, and tests can call the constructor directly with fake objects.
Note: Spring also supports field injection (
@Autowiredon a field) and setter injection. Prefer constructors; field injection hides dependencies and makes classes hard to test without Spring.
Choose Between Beans With @Primary and @Qualifier
If two beans match the same type, Spring cannot choose and startup fails.
package com.gocourse.spring;
import com.gocourse.spring.model.EmailNotifier;
import com.gocourse.spring.model.EnrollmentService;
import com.gocourse.spring.model.Notifier;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
public class QualifierDemo {
@Configuration
static class NotifierConfig {
@Bean
@Primary // the default when only the type is asked for
Notifier emailNotifier() {
return new EmailNotifier();
}
@Bean
Notifier smsNotifier() {
return (to, message) -> System.out.println("SMS to " + to + ": " + message);
}
@Bean
EnrollmentService enrollmentService(Notifier notifier) {
return new EnrollmentService(notifier); // receives emailNotifier (primary)
}
@Bean
EnrollmentService urgentEnrollmentService(@Qualifier("smsNotifier") Notifier notifier) {
return new EnrollmentService(notifier); // receives smsNotifier by name
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(NotifierConfig.class)) {
context.getBean("enrollmentService", EnrollmentService.class)
.enroll("meena@example.com", "Python");
context.getBean("urgentEnrollmentService", EnrollmentService.class)
.enroll("+91-98400-00000", "Python (batch starts today)");
}
}
}
Output:
EMAIL to meena@example.com: You are enrolled in Python
SMS to +91-98400-00000: You are enrolled in Python (batch starts today)
Without @Primary, startup fails with (shortened):
NoUniqueBeanDefinitionException: No qualifying bean of type 'com.gocourse.spring.model.Notifier' available:
expected single matching bean but found 2: emailNotifier,smsNotifier
How it works:
@Primarymarks the bean Spring picks when several match and nothing more specific is requested.@Qualifier("smsNotifier")asks for one bean by name and overrides@Primary.- Because
Notifierhas a single abstract method, a lambda is a perfectly valid bean.
Bean Scopes: Singleton vs Prototype
| Scope | Instances | Typical use |
|---|---|---|
singleton (default) | One per container, shared | Services, repositories, stateless helpers |
prototype | A new one on every getBean or injection | Objects that hold per-use state |
request, session | One per HTTP request or session | Web applications only |
package com.gocourse.spring;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
public class ScopeDemo {
static class ShoppingCart {
private static final AtomicInteger COUNTER = new AtomicInteger();
final int cartNumber = COUNTER.incrementAndGet();
final List<String> items = new ArrayList<>();
}
static class GstRates {
final double standard = 0.18;
}
@Configuration
static class ScopeConfig {
@Bean
@Scope("prototype")
ShoppingCart shoppingCart() { return new ShoppingCart(); }
@Bean // singleton by default
GstRates gstRates() { return new GstRates(); }
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(ScopeConfig.class)) {
ShoppingCart ashaCart = context.getBean(ShoppingCart.class);
ShoppingCart raviCart = context.getBean(ShoppingCart.class);
ashaCart.items.add("java");
System.out.println("Carts: " + ashaCart.cartNumber + " and " + raviCart.cartNumber);
System.out.println("Ravi's cart items: " + raviCart.items);
System.out.println("Same GstRates? " + (context.getBean(GstRates.class) == context.getBean(GstRates.class)));
}
}
}
Output:
Carts: 1 and 2
Ravi's cart items: []
Same GstRates? true
How it works:
- Each
getBean(ShoppingCart.class)call runs the@Beanmethod again, so Asha and Ravi get separate carts. GstRatesis a singleton, so one object is shared by everyone. Singletons are shared across threads, so keep them stateless or thread-safe.- Spring does not manage the end of a prototype bean's life; it creates it and hands it over.
Bean Lifecycle: Init and Destroy Methods
Spring can call a method after creating a bean and another before the context closes. This is useful for opening and closing resources.
package com.gocourse.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class LifecycleDemo {
static class ConnectionPool {
private final int size;
ConnectionPool(int size) { this.size = size; System.out.println("1. Constructor called"); }
void start() { System.out.println("2. Pool opened with " + size + " connections"); }
void stop() { System.out.println("4. Pool closed"); }
}
@Configuration
static class PoolConfig {
@Bean(initMethod = "start", destroyMethod = "stop")
ConnectionPool connectionPool() {
return new ConnectionPool(5);
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(PoolConfig.class)) {
System.out.println("3. Context ready, application running");
} // close() triggers destroy methods
}
}
Output:
1. Constructor called
2. Pool opened with 5 connections
3. Context ready, application running
4. Pool closed
How it works:
- Singletons are created eagerly while the context starts, so steps 1 and 2 happen inside the
AnnotationConfigApplicationContextconstructor. initMethodruns after all dependencies are injected, so it can safely use them.destroyMethodruns when the context closes.- Classes you own can use
@PostConstructand@PreDestroyinstead. Those annotations live injakarta.annotation-api, so add that dependency first.
Read Settings With @PropertySource and @Value
Hard-coded values belong in a properties file, not in Java code.
# src/main/resources/course.properties
course.name=Java Programming
course.fee=4999
course.tags=oop,web,spring
package com.gocourse.spring;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
public class PropertiesDemo {
record CourseInfo(String name, int fee, int seats, String[] tags) {}
@Configuration
@PropertySource("classpath:course.properties")
static class PropsConfig {
@Bean
CourseInfo courseInfo(@Value("${course.name}") String name,
@Value("${course.fee}") int fee,
@Value("${course.seats:30}") int seats, // default when missing
@Value("${course.tags}") String[] tags) {
return new CourseInfo(name, fee, seats, tags);
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(PropsConfig.class)) {
CourseInfo info = context.getBean(CourseInfo.class);
System.out.println(info.name() + " | fee " + info.fee() + " | seats " + info.seats());
System.out.println("Tags: " + Arrays.toString(info.tags()));
System.out.println("From Environment: " + context.getEnvironment().getProperty("course.fee"));
}
}
}
Output:
Java Programming | fee 4999 | seats 30
Tags: [oop, web, spring]
From Environment: 4999
How it works:
@PropertySourceloads the file into Spring'sEnvironment.${course.name}placeholders are then resolved from it.- Spring converts text to the parameter type:
"4999"becomes anint, and a comma-separated value becomes aString[]. ${course.seats:30}uses30because the file has nocourse.seatskey. Without a default, a missing key stops startup with an error, which catches typos early.- System properties and environment variables are part of the
Environmenttoo, so-Dcourse.fee=3999overrides the file.
Switch Beans With Profiles
A profile turns a group of beans on or off. Use it to print notifications in development and send real emails in production.
package com.gocourse.spring;
import com.gocourse.spring.model.EmailNotifier;
import com.gocourse.spring.model.EnrollmentService;
import com.gocourse.spring.model.Notifier;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
public class ProfileDemo {
@Configuration
static class EnvConfig {
@Bean
@Profile("dev")
Notifier consoleNotifier() {
return (to, message) -> System.out.println("[DEV - not sent] " + to + ": " + message);
}
@Bean
@Profile("prod")
Notifier emailNotifier() {
return new EmailNotifier();
}
@Bean
EnrollmentService enrollmentService(Notifier notifier) {
return new EnrollmentService(notifier);
}
}
static void runWithProfile(String profile) {
try (var context = new AnnotationConfigApplicationContext()) {
context.getEnvironment().setActiveProfiles(profile);
context.register(EnvConfig.class);
context.refresh(); // now the beans are created
context.getBean(EnrollmentService.class).enroll("karthik@example.com", "Spring");
}
}
public static void main(String[] args) {
runWithProfile("dev");
runWithProfile("prod");
}
}
Output:
[DEV - not sent] karthik@example.com: You are enrolled in Spring
EMAIL to karthik@example.com: You are enrolled in Spring
How it works:
- A bean with
@Profile("dev")exists only when thedevprofile is active, so exactly oneNotifieris created each time. - The profile must be set before
refresh(), which is why this example creates an empty context, sets the profile, registers the configuration and then refreshes. - Outside code, start the JVM with
-Dspring.profiles.active=prodto pick the profile without changing anything.
Real-World Example: Spring Framework Basics in a Discount Engine
A course platform applies several discount rules at checkout. New rules must be added without editing the checkout code. Spring can inject every bean of a type as a List, which makes this easy.
# src/main/resources/enroll.properties
enroll.early-bird-open=true
enroll.referred-students=asha,meena
enroll.max-discount=20
// DiscountRule.java
package com.gocourse.spring.discount;
public interface DiscountRule {
String name();
int percentFor(String student);
}
// EarlyBirdDiscount.java
package com.gocourse.spring.discount;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(1)
public class EarlyBirdDiscount implements DiscountRule {
private final boolean open;
public EarlyBirdDiscount(@Value("${enroll.early-bird-open:false}") boolean open) {
this.open = open;
}
public String name() { return "Early bird"; }
public int percentFor(String student) { return open ? 10 : 0; }
}
// ReferralDiscount.java
package com.gocourse.spring.discount;
import java.util.Set;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(2)
public class ReferralDiscount implements DiscountRule {
private final Set<String> referredStudents;
public ReferralDiscount(@Value("${enroll.referred-students:}") String[] referred) {
this.referredStudents = Set.of(referred);
}
public String name() { return "Referral"; }
public int percentFor(String student) { return referredStudents.contains(student) ? 15 : 0; }
}
// CheckoutService.java
package com.gocourse.spring.discount;
import java.util.List;
import java.util.StringJoiner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class CheckoutService {
private final List<DiscountRule> rules;
private final int maxDiscount;
public CheckoutService(List<DiscountRule> rules, @Value("${enroll.max-discount}") int maxDiscount) {
this.rules = rules;
this.maxDiscount = maxDiscount;
System.out.println("Discount rules loaded: " + rules.stream().map(DiscountRule::name).toList());
}
public void checkout(String student, int fee) {
int total = 0;
StringJoiner applied = new StringJoiner(" + ");
for (DiscountRule rule : rules) {
int percent = rule.percentFor(student);
if (percent > 0) {
total += percent;
applied.add(rule.name() + " " + percent + "%");
}
}
int finalPercent = Math.min(total, maxDiscount);
int price = fee * (100 - finalPercent) / 100;
String capNote = total > maxDiscount ? ", capped to " + maxDiscount + "%" : "";
System.out.println(student + ": " + (total == 0 ? "no discount" : applied + capNote) + " -> pays " + price);
}
}
// DiscountApp.java
package com.gocourse.spring.discount;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@ComponentScan
@PropertySource("classpath:enroll.properties")
public class DiscountApp {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(DiscountApp.class)) {
CheckoutService checkout = context.getBean(CheckoutService.class);
checkout.checkout("asha", 4999);
checkout.checkout("ravi", 4999);
checkout.checkout("meena", 2999);
}
}
}
Output:
Discount rules loaded: [Early bird, Referral]
asha: Early bird 10% + Referral 15%, capped to 20% -> pays 3999
ravi: Early bird 10% -> pays 4499
meena: Early bird 10% + Referral 15%, capped to 20% -> pays 2399
How it works:
- Scanning finds the rules.
@ComponentScanregisters bothDiscountRuleclasses and theCheckoutServicewithout a single@Beanmethod. - List injection. Because the constructor asks for
List<DiscountRule>, Spring injects all matching beans, sorted by@Order. Adding aFestivalDiscountclass with@Componentputs it into the list automatically;CheckoutServicenever changes. - Configuration outside code. The early-bird switch, referred students and discount cap come from
enroll.properties. Marketing can change them without recompiling. - Constructor injection everywhere. Every class gets its values through its constructor, so a unit test can call
new CheckoutService(List.of(new ReferralDiscount(new String[]{"asha"})), 20)with no Spring at all. - Next step. Spring Boot builds on exactly these ideas but creates the context, loads
application.propertiesand scans packages for you. Continue with the Spring Boot tutorial, and compare this approach with the hand-written wiring in the Java Web Application lesson.