Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
Chaturmind
← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: Fresher to 2 YearsSpring Framework Core
✓ FreeBeginner· 8 min read

Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Constructor vs setter injection, bean scopes and when to use them, prototype behaviour, singleton thread safety, multiple configuration files, design patterns in Spring, profiles, WebFlux vs MVC, and three real-project scenarios.

Published September 25, 2026


How to use this lesson

The second half of the Spring core questions is about lifecycle and environments: how long beans live, whether they're thread-safe, and how configuration changes between dev and prod. The three scenario questions at the end are common at companies that like "how would you…" rounds.

Q1. What's the difference between constructor injection and setter injection?

Short answer: Constructor injection supplies dependencies when the object is created. They're mandatory, can be final, and the object is never half-built. Setter injection supplies them after construction through setter methods. They're optional, and can be changed later.

@Service
class ReportService {
    private final ReportRepository repository;          // required → constructor
    private Clock clock = Clock.systemUTC();            // optional with a default → setter

    ReportService(ReportRepository repository) { this.repository = repository; }

    @Autowired(required = false)
    void setClock(Clock clock) { this.clock = clock; }  // tests can override it
}

Key points to cover:

  • Use constructors for required dependencies, and setters only for optional or reconfigurable ones.
  • Setter injection can work around circular dependencies, but a cycle usually signals a design problem.

Learn it in depth → Spring Dependency Injection

Q2. What bean scopes does Spring support?

Short answer:

  • singleton (the default): one instance per container.
  • prototype: a new instance every time the bean is requested.
  • Web-aware scopes:
    • request: one per HTTP request.
    • session: one per HTTP session.
    • application: one per ServletContext.
    • websocket: one per WebSocket session.
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
class RequestContext { private String correlationId; /* … */ }

Common trap: listing "global session". That scope existed only for Portlet applications, and was removed in Spring 5.

Key points to cover:

  • Injecting a shorter-lived bean (request or session scope) into a singleton needs a scoped proxy (proxyMode). Otherwise the singleton would capture a single instance forever.

Q3. When would you use singleton scope, and when prototype?

Short answer: Singleton for stateless services, repositories, clients and configuration, which is the vast majority of beans. Prototype for objects that hold per-use mutable state and must not be shared: a stateful builder or parser, or a command object that accumulates data.

Q4. What is the default bean scope?

Short answer: Singleton. Exactly one instance per Spring ApplicationContext, created eagerly at startup (unless marked @Lazy), and shared by everything that injects it.

Key points to cover:

  • Spring's singleton means one instance per container, not per JVM like the GoF Singleton pattern. Two contexts would hold two instances.

Q5. Are singleton beans thread-safe?

Short answer: Spring doesn't make them thread-safe. It creates one instance and shares it across all request threads. They're safe if they're stateless (only final references to other stateless beans), which is how Controller, Service and Repository beans should be written. Mutable fields in a singleton are shared by every request, and that causes race conditions.

@Service
class PricingService {
    private BigDecimal lastPrice;                     // ❌ shared across all request threads
    BigDecimal price(Order o) {
        BigDecimal p = calculate(o);                  // ✅ keep per-request data in local variables
        return p;
    }
}

Learn it in depth → Synchronized and Locks

Q6. Can a project have multiple Spring configuration files?

Short answer: Yes, and that's normal. Split configuration by concern (SecurityConfig, PersistenceConfig, KafkaConfig), and combine the pieces through component scanning or @Import(...). With XML, use <import resource="…"/>, or pass several files to the context.

Key points to cover:

  • In Spring Boot, any @Configuration class under the main application's package is picked up automatically, and @Profile can switch whole configuration classes on or off.

Q7. Name some design patterns used in the Spring framework.

Short answer:

PatternWhere in Spring
SingletonThe default bean scope
FactoryBeanFactory, FactoryBean, @Bean methods
ProxyAOP: @Transactional, @Cacheable, @Async are implemented with JDK or CGLIB proxies
Template MethodJdbcTemplate, RestTemplate, TransactionTemplate
ObserverApplicationEvent and @EventListener
Front ControllerDispatcherServlet
StrategyPluggable PlatformTransactionManager, HandlerMapping and ViewResolver implementations
Dependency InjectionThe whole container

Learn it in depth → Spring AOP

Q8. How does the prototype scope work?

Short answer: Every time a prototype bean is requested from the container (by getBean, or by being injected into another bean), Spring creates a new instance and injects its dependencies. Then Spring hands it over and stops managing it: @PreDestroy methods are not called for prototypes.

Common trap: injecting a prototype into a singleton. The injection happens only once, so the singleton keeps the same "prototype" instance forever. To get a fresh instance each time, use ObjectProvider<T> (provider.getObject()), @Lookup methods, or a scoped proxy.

@Service
class ImportService {
    private final ObjectProvider<CsvParser> parsers;          // CsvParser is @Scope("prototype")
    ImportService(ObjectProvider<CsvParser> parsers) { this.parsers = parsers; }
    void importFile(Path p) { parsers.getObject().parse(p); } // a new parser per import
}

Q9. What are Spring profiles, and how do you use them?

Short answer: Profiles let you register beans or load configuration only in certain environments, such as dev, test or prod. Annotate beans or configuration classes with @Profile("dev"), put per-environment properties in application-dev.yml, and activate profiles with spring.profiles.active.

@Configuration
@Profile("dev")
class DevDataConfig {
    @Bean CommandLineRunner seed(ProductRepository repo) { return args -> repo.saveAll(sampleProducts()); }
}
java -jar app.jar --spring.profiles.active=prod        # or SPRING_PROFILES_ACTIVE=prod

Key points to cover:

  • Profile expressions are supported: @Profile("!prod"), @Profile("cloud & kafka").
  • Don't hard-code secrets in profile files. Inject them from environment variables or a secrets manager.

Q10. What is Spring WebFlux, and how is it different from Spring MVC?

Short answer: WebFlux (Spring 5+) is Spring's reactive, non-blocking web stack, built on Project Reactor (Mono, Flux), and usually run on Netty. Spring MVC is the servlet-based, blocking, thread-per-request stack. WebFlux handles many concurrent connections with a small number of threads, but only if everything in the call chain is non-blocking.

Spring MVCSpring WebFlux
ModelBlocking, thread per requestNon-blocking, event loop
TypesResponseEntity<Order>Mono<Order>, Flux<Order>
ServerTomcat, Jetty (Servlet API)Netty (or servlet containers in async mode)
Data accessJDBC/JPAR2DBC, reactive Mongo/Redis, WebClient
Best forMost CRUD and business appsStreaming, huge numbers of mostly idle connections, gateways

Key points to cover:

  • Calling blocking JDBC from a WebFlux handler stalls the event loop. That's the classic mistake.
  • Since Java 21, Spring MVC with virtual threads (spring.threads.virtual.enabled=true) gives similar scalability with simple blocking code. That's often the pragmatic choice today.

Q11. Scenario: annotations or XML to configure beans on a new project?

Short answer: Annotations and Java config for virtually all new projects. They're type-safe, refactor-friendly, sit next to the code, and are what Spring Boot is built around. XML survives mainly in legacy systems, or when wiring must change without recompiling (which externalised properties usually handle better).

Key points to cover:

  • Decision factors: team familiarity, existing codebase conventions, and whether configuration must be changed by operations staff without a build.

Q12. Scenario: a large project has many interdependent beans. How do you keep dependencies clean?

Short answer:

  • Use constructor injection throughout, so dependencies are visible.
  • Depend on interfaces.
  • Organise code by feature, with a configuration class per module, and expose only the module's public services.
  • Use profiles for environment differences.
  • Watch for cycles and "god services".

Key points to cover:

  • Use events (ApplicationEventPublisher) to decouple modules that only need to notify each other.
  • Tools such as ArchUnit, or Spring Modulith, can verify module boundaries in tests.

Q13. Scenario: a singleton bean must be thread-safe. What are your options?

Short answer:

  1. Make it stateless, keeping per-request data in local variables or method parameters. This is the best option.
  2. If shared state is unavoidable, use concurrent structures (ConcurrentHashMap, AtomicLong).
  3. Guard compound updates with synchronized or a ReentrantLock.
  4. Use ThreadLocal for per-thread data, and always clear it in a finally block, because pooled threads are reused.
  5. Or change the scope, to request or prototype.

Key points to cover:

  • Mutable state on a singleton also breaks horizontal scaling, because every instance of the app has its own copy. Shared state usually belongs in a database or cache (Redis).

Follow-up questions this topic invites — and their answers

Q: What does @Lazy do? A: It delays creating a singleton bean until it's first needed, instead of at startup. That speeds up startup, but hides configuration errors until runtime. On an injection point, it injects a lazy-resolving proxy.

Q: What are @PostConstruct and @PreDestroy? A: Lifecycle callbacks. The first runs after dependencies are injected, for initialisation such as warming a cache. The second runs before a singleton is destroyed at shutdown, for cleanup. They come from jakarta.annotation in Spring 6.

Q: How do you read a property value in a bean? A: @Value("${app.page-size:20}") for single values, with a default after the colon, or a type-safe @ConfigurationProperties(prefix = "app") class (often a record) for groups of related settings.

Q: Can you change the active profile at runtime? A: Not for an already started context. Profiles are evaluated when the context starts. To change configuration at runtime, use Spring Cloud Config with refresh scope, or feature flags.

Previous

Spring IoC, Dependency Injection & Beans — Interview Questions

Next

Spring Boot Fundamentals — Interview Questions

AI Tutor

Lesson: Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.