Prof. (Dr. ) Harish Kumar MittalProfessor · Researcher · Educator

Project Based Learning in Java

Spring Core, Dependency Injection and Bean Lifecycle

Spring Framework provides reusable infrastructure for building Java applications. Spring Core includes the container that creates and connects application objects, called beans. Inversion of Control (IoC) gives this responsibility to the container. Dependency Injection (DI) means supplying an object with the other objects it needs, usually through its constructor.

Inversion of Control (IoC) lets a framework create and manage application objects. In Spring, the container supplies these objects to the classes that need them.

Understand how the Spring container creates, connects and manages application objects.

Part 1: Spring IoC and Dependency Injection

Key concepts

Dependency
An object or capability another object needs to do its work.
IoC
Inversion of Control: infrastructure takes responsibility for tasks such as creating and assembling application objects.
DI
Dependency Injection: supplying a needed object from outside the object that uses it.
Bean
An object managed by the Spring container; it is not simply any object created with new.

Ask two questions separately: who creates the service, and who supplies its repository? With constructor injection, the service states what it needs in its constructor. Spring chooses a compatible registered bean and supplies it. The service can then focus on its business operation.

Example: A test can supply a small in-memory repository while the application supplies a database repository. Both satisfy the same interface. The service need not choose either implementation.

Example: Constructor injection

This example supplies a dependency through a constructor. It runs as plain Java; the later Spring examples show how the container supplies that dependency.

Save as InjectionDemo.java. With Java 17 or later, run javac InjectionDemo.java, then java InjectionDemo.

public class InjectionDemo {
    interface Names { String first(); }
    static class Greeting {
        private final Names names;
        Greeting(Names names) { this.names = names; } // Supply the dependency.
        String message() { return "Hello, " + names.first(); }
    }
    public static void main(String[] args) {
        Names sample = () -> "Asha"; // A tiny substitute for a repository.
        Greeting greeting = new Greeting(sample);
        System.out.println(greeting.message()); // The service uses its collaborator.
    }
}

Expected output

Hello, Asha

Explain container-managed objects and compare constructor, setter and field injection.

Chapter 3.1 · Lesson 2 CO5 aligned Unit 3 · Chapter 3.1

Course Outcome (CO) states what a learner should be able to do after the course; CO1 to CO5 label the five syllabus outcomes.

Learning outcome: Explain container-managed objects and compare constructor, setter and field injection.

Start here: Start with one relationship: StudentService needs StudentRepository. Learn who creates the objects, how the repository reaches the service, and why constructor injection makes that requirement clear.

Introduction

Objects in an application work together. A controller calls a service; the service uses a repository to access data. The repository is a dependency of the service because the service needs it to do its work.

If every class creates its own collaborators, the choice of implementation becomes scattered through the code. Supplying those collaborators from outside makes them easier to replace and test.

Spring Framework is a modular Java application framework that provides infrastructure for assembling application objects and supporting concerns such as transactions, data access and web request handling. Its Core container implements Inversion of Control and dependency injection. Application classes can concentrate on their own operations while the container assembles their collaborators.

This lesson introduces those terms before comparing injection techniques. It builds on Java classes, constructors, interfaces and composition. Spring Boot is introduced in Lesson 3; it uses Spring Framework and simplifies application configuration and startup.

Learning objectives

After completing this lesson, you should be able to:

Dependency Injection (DI) supplies an object's collaborators from outside instead of having the object construct them itself.

  1. Define a dependency, coupling, IoC, DI and a Spring bean.
  2. Explain what the Spring IoC container and ApplicationContext manage.
  3. Distinguish registering a bean from injecting a dependency.
  4. Compare constructor, setter and field injection.
  5. Explain how type matching, qualifiers and primary beans affect dependency selection.

Key terms and definitions

Term Definition Example or significance
Framework Reusable software infrastructure that provides conventions and execution points for application code. Spring invokes configured components through its infrastructure.
Dependency An object or capability that another object needs to perform its work. StudentService needs a StudentRepository.
Coupling The degree to which a component depends on the details of another component. Constructing a specific database implementation inside a service ties them together.
Inversion of Control (IoC) An arrangement in which infrastructure takes responsibility for control that application code would otherwise manage directly. Spring creates and wires configured application objects.
Dependency injection (DI) Supplying an object's collaborators from outside rather than having that object create or locate them itself. Passing a repository to a service constructor.
Spring bean An object instantiated, assembled and managed by the Spring IoC container. A registered StudentService instance.
IoC container The infrastructure that reads configuration and creates, wires and manages beans. An ApplicationContext implementation.
Bean definition Configuration metadata describing how a bean is created and configured. Its type, scope and constructor dependencies.
BeanFactory Spring's foundational container interface for bean management and lookup. Provides the basic container contract.
ApplicationContext A BeanFactory subinterface with additional application facilities. Events, message resources and integration with framework infrastructure.
Annotation Metadata attached to Java code and interpreted by a compiler, tool or runtime framework. Spring interprets @Component and @Autowired.
Component scanning Searching configured packages for eligible annotated components and registering their definitions. Finding a service in the application's package tree.
Autowiring Resolving and supplying a managed dependency according to injection metadata and eligible candidates. Selecting a bean compatible with a constructor parameter.
Qualifier Metadata used to narrow the set of eligible injection candidates. Choosing one of two repository implementations.

DI is one form of IoC. It can also be performed manually in ordinary Java: a caller can construct a repository and pass it to a service. Spring adds container-managed assembly; DI does not require every class to know about the container.

  1. Create: a caller creates an object that implements the repository contract.
  2. Supply: the caller passes that object to the service constructor.
  3. Use: the service calls the supplied repository instead of choosing and creating a storage implementation itself.

This is manual DI. With Spring, the container performs the creation and supply steps from your configuration. The service still declares the dependency it needs.

From direct construction to injected collaboration

Java Database Connectivity (JDBC) is Java's standard interface for connecting to relational databases, issuing statements and reading results.

Consider a service that creates a concrete JDBC repository internally. The service controls both its business operation and the choice of storage implementation. Changing storage or testing with an in-memory substitute then requires changes to its construction logic.

With injection, the service declares the collaborator it needs. A caller or container chooses and supplies an implementation. Depending on an interface can reduce reliance on implementation details, provided that the interface expresses a useful contract. DI does not eliminate all coupling: the service still depends on that contract.

In the chapter project, the service declares a StudentRepository dependency and Spring Data provides an eligible implementation. Spring assembles the service with that repository. Hibernate-managed entity instances remain distinct from Spring-managed service beans.

ApplicationContext
 ├─ StudentRepository implementation
 └─ StudentService(repository)

For this lesson, focus on Core/Beans, which describes and assembles beans, and Context, which adds application-level services. Spring Expression Language (SpEL) evaluates expressions.

Object-Relational Mapping (ORM) maps objects in a program to rows and relationships in a database. Model-View-Controller (MVC) separates application data and rules, user-facing presentation, and request or input handling.

The other modules provide context for later study: data-access support integrates JDBC, transactions and ORM; Spring MVC handles servlet-based web requests; WebFlux provides a reactive web stack; and Spring Test supports unit and integration tests.

Aspect-oriented programming (AOP) separates cross-cutting behaviour from the main operation. An aspect groups such behaviour; advice is the action applied, and a pointcut selects where it applies. Spring AOP commonly uses proxies around method calls. Transaction interception is a practical example: begin/join a transaction, invoke the service and then commit or roll back. Proxy interception has limitations, including ordinary self-invocation.

Simple Object Access Protocol (SOAP) is the historical expansion of SOAP, a protocol for structured messages using Extensible Markup Language envelopes. Representational State Transfer (REST) is an architectural style that organises a web service around resources, such as students or products, accessed through a consistent interface.

Spring Data, Security, Integration, Batch and Cloud are related Spring projects, not all modules embedded in Spring Core. They address persistence repositories, access control, messaging, batch work and distributed-system support respectively. Spring Web Services focuses on SOAP; ordinary REST applications use MVC or WebFlux. Using one Spring project does not automatically enable all of them.

Configuration styles

Extensible Markup Language (XML) represents structured data using named elements and attributes.

Spring accepts XML bean definitions, component annotations and Java configuration. XML uses bean definitions, constructor-arg for constructor values and property for setter properties. Java configuration uses @Configuration and @Bean; scanning discovers components annotated with stereotypes. These styles can be combined when required.

For example, an XML definition can declare a service with a constructor reference to a repository. The equivalent Java configuration supplies that repository as a factory-method parameter. Injection is the dependency relationship; XML or Java annotations are ways of describing it. A manually configured container can read XML with ClassPathXmlApplicationContext; older XmlBeanFactory examples should not be copied into the chapter's modern Spring baseline.

Container responsibilities

Think of a bean definition as a recipe and a bean instance as the object made from that recipe. The container reads the configuration, records the recipes, resolves dependencies and creates the objects.

Bean post-processors can then inspect or wrap an object. A wrapper called a proxy can add behaviour such as transaction handling around a method call. Application services normally receive their dependencies through injection; they do not repeatedly ask the container to find them.

A small context can be started without Boot. The following fragment loads the CourseConfiguration class from the bean lesson and retrieves its Clock bean:

try (AnnotationConfigApplicationContext context =
        new AnnotationConfigApplicationContext(CourseConfiguration.class)) {
    Clock clock = context.getBean(Clock.class);
    System.out.println(clock.getZone());
}

Coordinated Universal Time (UTC) is the international reference time standard used to express timestamps consistently.

Import java.time.Clock and org.springframework.context.annotation.AnnotationConfigApplicationContext. The zone printed is Z for the configured UTC clock. Closing the context triggers managed cleanup. Normal application services should receive dependencies through injection rather than repeatedly looking them up from the context.

Compare dependency injection choices

Consider a service that needs a repository. Select a style, then compare its construction and testing implications with the code examples below.

Constructor injection

The caller must supply the repository when constructing the service. The dependency can be final, and plain Java tests can supply a substitute. This is usually the clearest choice for a required collaborator.

Setter injection

The collaborator is supplied after construction. This permits reconfiguration, but the object needs a well-defined usable state. An Autowired setter is required by default; optionality must be configured deliberately.

Field injection

The container populates the field. The constructor does not reveal the dependency, and a plain new call leaves it unpopulated unless another mechanism supplies it. Constructor injection generally makes required dependencies and tests clearer.

Constructor injection for required collaborators

@Service
public class StudentService {
    private final StudentRepository students;
    public StudentService(StudentRepository students) {
        this.students = students;
    }
}

This is a fragment of the full service developed later. Its repository requirement is visible and the field can be final. A single constructor needs no @Autowired in modern Spring. A plain unit test can construct it with a suitable test repository. Automatic transaction interception, however, requires a managed/proxied service.

Setter and field alternatives

@Autowired
public void setStudents(StudentRepository students) {
    this.students = students;
}

Setter injection permits wiring after construction. An @Autowired setter is required by default; optional injection must be chosen explicitly. For required collaborators, a constructor usually makes the class contract clearer.

@Autowired
private StudentRepository students;

Field injection hides the dependency from callers and makes plain Java construction/testing less convenient. These are alternative designs: do not add all three forms to the same service. An annotation on an object created with new does not automatically cause Spring to inject it.

Resolving a bean

Spring primarily matches by type. If two implementations are eligible, use @Qualifier at the injection point or @Primary on a default bean. A qualifier narrows candidates; it does not create a missing implementation.

If Spring reports that a dependency is missing, check the configuration before changing the injection style:

  1. Is the implementation registered through a component annotation, a factory or another supported mechanism?
  2. Does component scanning include its package?
  3. Is the required profile active, and has the configuration been imported?

In the Boot example, put the application class in a parent package of the application components. A constructor cycle, such as A needing B while B needs A, normally prevents creation; separate the responsibilities instead of adding more injection annotations.

Registration versus injection

Application Programming Interface (API) defines the operations one software component can use to communicate with another. Java Persistence API (JPA) lets Java code save and load objects as database rows. The standard is now called Jakarta Persistence.

@Component and @Bean register bean definitions. @Autowired marks an injection point. These solve different steps of assembly. The service's repository interface is implemented at runtime by Spring Data JPA; an arbitrary Java interface without an implementation or factory is not injectable by itself.

Summary

Spring assembles managed objects from configuration metadata. IoC describes the transfer of control, and DI supplies collaborators from outside an object. Bean registration, dependency selection and injection are separate steps. Constructor injection makes required dependencies explicit.

Practice

  1. Draw Controller → Service → Repository dependencies.
  2. Convert a field-injected service to constructor injection.
  3. Explain how Qualifier resolves two eligible implementations.

Quick check

Check your understanding

Are IoC and DI identical? DI is a way to provide collaborators; IoC is the broader transfer of control to a container or framework.

Further reading

Review questions

1. Does @Autowired create an implementation for every Java interface?

Answer: No. It requests injection. A compatible implementation must already be registered or supplied by a supported factory, such as Spring Data.

2. Why is constructor injection useful for a required dependency?

Answer: An object cannot be constructed normally without that dependency, and a test can supply it explicitly. The dependency is visible in the class contract.

Part 2: Spring Beans, Configuration and Lifecycle

Key concepts

Bean definition
Configuration describing how Spring should create and configure a bean.
Lifecycle callback
A method invoked at a defined stage, such as after dependencies have been supplied or during normal shutdown.
Scope
The rule that determines when a new instance is created and when an existing one is reused.
Singleton scope
One instance per bean definition within one Spring container, not one instance across every application or server.

Read bean management in order: register a definition → create the object → supply dependencies → initialise → use → perform eligible cleanup. Registration and injection are different steps. Scope determines sharing; it does not automatically make shared state thread-safe.

Example: @Bean suits a Clock supplied by a Java library because you cannot add @Component to that library class. A configuration method creates the Clock and returns it for Spring to manage.

Register beans, explain stereotypes and scope, and trace initialisation and destruction.

Chapter 3.1 · Lesson 2 CO5 aligned Unit 3 · Chapter 3.1

Learning outcome: Register beans, explain stereotypes and scope, and trace initialisation and destruction.

Start here: Register the Clock bean, trace CourseBanner from startup to shutdown, then compare bean scopes. The later annotation lists are reference material.

Registering a component

In Part 1, a bean was introduced as an object managed by Spring. Here, separate three questions: How is it registered? When is it initialised and cleaned up? How long is it shared?

Use component scanning for suitable classes you own. Use a configuration factory method when you need explicit construction or a Java-library object such as Clock. Both routes let Spring manage the resulting bean.

Annotation Meaning
@Component General managed component
@Service Component representing application/business operations
@Repository Persistence component, eligible for exception translation when infrastructure is configured
@Configuration Class containing bean configuration
@Bean Factory method whose result is registered as a bean
@Autowired Dependency injection point

@Service does not automatically make every method transactional. A Spring Data repository interface normally needs no explicit @Repository; repository scanning creates its implementation.

Stereotypes and persistence exceptions

Data Access Object (DAO) is a component that separates database operations from business logic.

@Component is the general scanning stereotype. @Service and @Repository specialise it to communicate application and persistence roles. A handwritten DAO can use @Repository; Spring Data repository interfaces normally do not need it because repository scanning registers their implementations.

Repository exception translation adapts supported persistence-provider exceptions to Spring's DataAccessException hierarchy when the required translation infrastructure is configured. The annotation does not create a database connection, implement arbitrary DAO methods or make an operation transactional by itself.

Configuration example

Clock is a Java library class, so register it with a factory method:

package edu.pblj.unit3;

import java.time.Clock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CourseConfiguration {
    @Bean
    public Clock clock() { return Clock.systemUTC(); }
}

The method returns the object that Spring manages. Its default bean name is clock, and Spring can supply it wherever an eligible dependency needs a Clock, such as the error handler.

Configuration detail: full @Configuration classes can intercept calls between bean methods so those calls respect the configured bean scope. With proxyBeanMethods=false, a direct call is an ordinary Java method call. Prefer declaring another bean as a factory-method parameter instead of depending on intercepted calls.

Lifecycle callbacks

A lifecycle is the sequence from creating a bean to cleaning it up. Spring first resolves constructor dependencies and constructs the object. It then supplies any setter or field dependencies and runs initialisation callbacks.

Bean post-processors participate around initialisation and may expose a proxy, for example for transaction handling. The bean is then ready for use. On normal context shutdown, Spring runs eligible destruction callbacks to release resources.

package edu.pblj.unit3;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class CourseBanner {
    private final String label;
    public CourseBanner(@Value("${course.label}") String label) {
        this.label = label;
    }
    @PostConstruct
    void ready() { System.out.println("Ready: " + label); }
    @PreDestroy
    void closing() { System.out.println("Closing: " + label); }
}

Project Based Learning in Java (PBLJ) is this course, which develops Java programming skills through concepts, examples and practical projects.

This component reads course.label from application.properties. Startup includes Ready: PBLJ Chapter 3.1; normal shutdown includes Closing: PBLJ Chapter 3.1, alongside framework logs. @PostConstruct runs after injection. A constructor cannot assume fields intended for later injection are already populated. A forcibly terminated process may not execute cleanup callbacks.

Initialisation and destruction alternatives

The chapter uses Jakarta @PostConstruct and @PreDestroy. A bean factory method can also declare @Bean(initMethod = "open", destroyMethod = "close") when the returned class provides those methods. Spring-specific InitializingBean and DisposableBean interfaces offer callback methods too. Choose the callback mechanism deliberately; duplicating the same work across several callbacks can initialise or release a resource more than once.

Bean lifecycle walkthrough

Follow each stage and read what the container does.

  1. InstantiateResolve constructor dependencies and construct the bean.
  2. PopulateSupply setter and field dependencies.
  3. InitialiseRun callbacks and post-processors.
  4. UseInvoke the managed object or its proxy.
  5. DestroyRun eligible managed cleanup.

Spring selects the constructor/factory and resolves required constructor arguments as part of creating the object.

Scope and state

Java Virtual Machine (JVM) runs Java bytecode, the instructions produced by a Java compiler, and manages runtime tasks such as memory allocation.

Singleton is the default scope: one shared instance for a bean definition in a container. It does not mean one object for the entire JVM, and it does not make the object thread-safe.

Prototype creates a new instance each time that bean is requested from the container. If Spring injects a prototype once into a singleton, that singleton keeps the supplied instance; it does not receive a new one on every service call. Spring does not automatically run prototype destruction callbacks, so the code using those resources must arrange cleanup.

Request and session scopes need a web-aware context. A stateless service normally fits singleton scope. A field named currentStudent would make that service unsafe under concurrent requests unless access were designed appropriately. Keep request data in parameters and local variables.

Container comparison and creation timing

Reference detail: read the comparison and annotation catalogue after tracing the lifecycle example. They explain infrastructure choices; they are not extra steps to add to every bean.

Capability Basic BeanFactory setup ApplicationContext
Create and look up beans Yes Yes
Apply dependency metadata Yes, with relevant configuration infrastructure Yes
Automatically discover/register infrastructure post-processors Requires explicit setup at the basic factory level Supported during context startup
Application events and message resources Not supplied by the basic BeanFactory contract Provided by the context
Typical eager creation Depends on how the factory is used Non-lazy singleton beans are normally created on refresh

Aspect-Oriented Programming (AOP) separates shared behaviour, such as logging or transaction handling, from the main business operation.

It is too broad to say BeanFactory can never support AOP: a factory can apply suitably registered post-processors. ApplicationContext provides the convenient infrastructure integration normally used by applications. @Lazy can defer a bean's creation, although an eager dependent may still require its creation. Constructor dependencies are resolved as part of construction; setter/field injection follows construction. A normal business method is used after initialisation, not automatically invoked as an extra lifecycle phase.

Additional annotation vocabulary

Use this section as a reference after you understand registration, lifecycle and scope. You do not need to use all these annotations in one application.

Annotation Role
@Scope Choose a bean lifetime such as prototype
@Lazy Defer initialisation or provide lazy dependency resolution, depending on placement
@Value Inject a configured value or expression result
@Profile Register configuration only for matching active profiles
@Import Include additional configuration/component definitions
@ImportResource Read bean definitions from XML resources
@PropertySource Add a properties resource to the Environment; it does not replace Boot's configuration-loading rules
@ComponentScan Select packages to search for eligible components
@Lookup Container-supplied method lookup, sometimes used to obtain a fresh prototype from a singleton

@Qualifier narrows injection candidates and @Primary chooses a preferred candidate; they do not create beans. The old @Required annotation is not the modern way to express a required dependency: use a constructor contract. Request, session, application and WebSocket scopes are web-aware lifetimes. Historical portlet globalSession scope is not part of the current scope set used here.

Other annotation families in the reference material

Boot uses @EnableAutoConfiguration and conditions such as @ConditionalOnClass and @ConditionalOnMissingBean; @ConfigurationProperties binds grouped settings. Scheduling uses @EnableScheduling/@Scheduled; asynchronous execution uses @EnableAsync/@Async with suitable executor configuration. These features require their infrastructure and are not enabled by placing arbitrary annotations on unmanaged objects.

Application Programming Interface (API) defines the operations one software component can use to communicate with another. Java Persistence API (JPA) lets Java code save and load objects as database rows. The standard is now called Jakarta Persistence. Cross-Origin Resource Sharing (CORS) is the browser mechanism that lets a server permit selected requests from another origin.

Persistence vocabulary includes @Query, @Modifying, @Procedure, @Lock and @EnableJpaRepositories. MongoDB's @Document and @Field belong to a different store-specific model; they do not replace JPA's @Entity and @Column. Web annotations such as @RequestMapping, @PathVariable, @RequestBody, @ResponseBody, @RequestParam, @ModelAttribute, @ResponseStatus and @CrossOrigin describe request mapping, binding, responses or CORS. Their web/API use is developed in Chapter 3.2. CORS configuration is not authentication.

Compare two runs

Change course.label, restart the application and identify the changed callback output. Register a second Clock bean without choosing a default and observe the dependency ambiguity; resolve it with a qualifier or primary bean. Restore the original setup before continuing the chapter.

Summary: register the object so Spring can manage it, supply its dependencies, initialise it and then use it. Scope determines how instances are shared. Eligible destruction callbacks run during normal shutdown; prototype cleanup must be arranged by the code using it.

Practice

  1. Explain why Clock uses @Bean rather than Component.
  2. Trace normal startup and shutdown callbacks.
  3. Explain why singleton does not mean thread-safe.

Quick check

Check your understanding

Does Spring call prototype destruction callbacks automatically? No. The client must arrange cleanup for prototype resources.

Further reading

Review questions

1. Does @Service automatically make a method transactional?

Answer: No. It identifies a service component. Transaction behaviour requires transaction configuration and a suitable @Transactional boundary.

2. Will Spring automatically run destruction callbacks for every prototype bean?

Answer: No. The client using a prototype must arrange its resource cleanup. Normal managed singleton shutdown has different lifecycle handling.