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: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
Chaturmind
← Java Interview Prep: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 2–5 YearsSpring Framework In Depth
✓ FreeIntermediate· 8 min read

Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Resolving bean conflicts, what really happens when auto-configurations define the same bean, XML vs annotations, Mockito @Spy vs @Mock, join points vs pointcuts, Spring Batch end to end, how @Autowired resolves dependencies, why constructor injection wins, AOP and its biggest drawback, and preventing cyclic dependencies.

Published September 25, 2026


How to use this lesson

These questions test whether you understand Spring's resolution rules: which bean gets injected, and which configuration wins. They also test cross-cutting features (AOP, Batch). Several common answers are outdated for Spring Boot 2.1+, so give the current behaviour.

Q1. Scenario: two beans conflict in your application. How do you resolve it in Spring Boot?

Short answer: First, identify the kind of conflict:

  • Two beans of the same type (NoUniqueBeanDefinitionException): mark the default with @Primary, or pick one at the injection point with @Qualifier. Or inject a List/Map of all of them, and choose at runtime.
  • Two bean definitions with the same name (BeanDefinitionOverrideException): rename one of them. Or, only if you really intend an override, set spring.main.allow-bean-definition-overriding=true.
  • An auto-configured bean you want to replace: just define your own bean. Auto-configuration backs off (@ConditionalOnMissingBean).

Q2. What happens if several auto-configuration classes define the same bean?

Short answer: Well-written auto-configurations guard their beans with @ConditionalOnMissingBean. The first one to be evaluated registers the bean, and the others back off. The evaluation order is controlled by @AutoConfiguration(before = …, after = …) / @AutoConfigureOrder. User configuration is always processed before auto-configuration, so your beans take priority.

If two definitions actually collide by name without such conditions, Spring Boot (since 2.1) fails at startup, because bean-definition overriding is disabled by default.

Common trap: "the last one read wins". That was plain Spring's historical behaviour (silent overriding), and Boot deliberately turned it off, because silent overrides caused hard-to-find bugs.

Learn it in depth → Auto-Configuration Mechanism

Q3. XML or annotations for configuration: which do you prefer, and why?

Short answer: Annotations and Java configuration. They're type-safe (refactoring and IDE navigation work), sit next to the code they configure, can use conditions and profiles in code, and are what Spring Boot is designed around. XML still appears in legacy systems. Its original selling point (changing wiring without recompiling) is now served better by externalised properties and profiles.

Key points to cover:

  • Use @Configuration classes for third-party objects and wiring decisions, and stereotypes plus constructor injection for your own classes.

Q4. What's the difference between @Spy and @Mock in Mockito?

Short answer: A @Mock is a complete fake. Every method returns a default (null, 0, an empty collection) unless you stub it, and no real code runs. A @Spy wraps a real object. Real methods run, unless you stub specific ones.

@Spy List<String> spyList = new ArrayList<>();
@Mock List<String> mockList;

spyList.add("a");        // really added → spyList.size() == 1
mockList.add("a");       // does nothing → mockList.size() == 0 (unstubbed default)

doReturn(100).when(spyList).size();      // use doReturn with spies: when(spy.size()) would call the real method first

Key points to cover:

  • A spy is often a sign of a class that's hard to test (it does too much). Prefer mocks for collaborators, and real objects for simple values.

Learn it in depth → Mockito Basics

Q5. What's the difference between a join point and a pointcut in Spring AOP?

Short answer: A join point is a point in program execution where an aspect could apply. In Spring AOP, it's always a method execution on a Spring bean. A pointcut is an expression that selects a set of join points. Advice is the code that runs at the selected join points (@Before, @AfterReturning, @AfterThrowing, @After, @Around). An aspect bundles pointcuts and advice.

@Aspect
@Component
class TimingAspect {
    @Pointcut("within(com.shop..service..*) && execution(public * *(..))")   // the pointcut: which join points
    void serviceMethods() { }

    @Around("serviceMethods()")                                               // the advice
    Object time(ProceedingJoinPoint jp) throws Throwable {                    // jp = the current join point
        long start = System.nanoTime();
        try { return jp.proceed(); }
        finally { log.info("{} took {} µs", jp.getSignature().toShortString(), (System.nanoTime() - start) / 1000); }
    }
}

Learn it in depth → Spring AOP

Q6. What is Spring Batch used for? Describe how you'd implement a batch job.

Short answer: Spring Batch processes large volumes of data reliably in the background: nightly settlements, file imports, report generation, data migrations. It provides chunk-oriented processing, restartability (it tracks progress in its job repository tables), skip and retry policies, and partitioning for scale.

The steps:

  1. Define a Job, made of one or more Steps.
  2. For a chunk step, configure an ItemReader (a flat file, JDBC cursor or paging reader), an ItemProcessor (validation and transformation) and an ItemWriter (a database, file or API), plus a chunk size. Each chunk is committed in its own transaction.
  3. Add fault tolerance: skip for bad records (with a limit), retry for transient errors, and listeners for logging.
  4. Launch it from a scheduler, or on an event, with job parameters (such as the business date), so reruns are idempotent. Monitor it through the job repository.
@Bean
Step importTransactions(JobRepository repo, PlatformTransactionManager tx,
                        FlatFileItemReader<TxnLine> reader, TxnProcessor processor, JdbcBatchItemWriter<Txn> writer) {
    return new StepBuilder("importTransactions", repo)
            .<TxnLine, Txn>chunk(500, tx)
            .reader(reader).processor(processor).writer(writer)
            .faultTolerant().skip(ParseException.class).skipLimit(100)
            .retry(TransientDataAccessException.class).retryLimit(3)
            .build();
}

Key points to cover:

  • Batch 5 (Boot 3) removed JobBuilderFactory and StepBuilderFactory. You pass the JobRepository explicitly, as shown above.

Q7. What kind of injection does @Autowired perform?

Short answer: @Autowired resolves a dependency by type. If several beans match, it narrows the choice using @Qualifier, then @Primary, then the parameter or field name as a fallback. It can be applied to a constructor, a setter or other method, or a field, and the injection style is whichever you annotate. Since Spring 4.3, a class with a single constructor gets constructor injection even without @Autowired.

Common trap: "@Autowired uses constructor injection by default". The annotation has no default style. Constructor injection is the recommended practice.

Q8. Why is constructor injection recommended over setter injection?

Short answer:

  • Required dependencies are enforced, so the object can never exist half-configured.
  • final fields make it immutable, and safe to publish across threads.
  • It's easily testable without Spring: new Service(mockA, mockB).
  • It makes design problems visible: a ten-argument constructor says the class does too much, and circular dependencies fail fast.

Setter injection remains useful for optional or re-configurable dependencies.

Q9. Define AOP, and state its biggest disadvantage.

Short answer: Aspect-Oriented Programming modularises cross-cutting concerns (transactions, security, logging, metrics, caching, retries) into aspects that are applied declaratively, instead of being scattered through the business code. In Spring, AOP powers @Transactional, @Cacheable, @Async, @PreAuthorize and @Retryable.

Its biggest disadvantage: hidden control flow. Behaviour happens without appearing in the code you're reading, which makes debugging and onboarding harder. Spring's proxy-based implementation adds pitfalls:

  • Self-invocation skips the aspect.
  • final and private methods aren't advised.
  • The order of several aspects matters (@Order).
  • Proxies add a small overhead, and extra stack frames.

Q10. How can you prevent cyclic dependencies in Spring?

Short answer:

  • Design with clear layering: controllers → services → repositories, with dependencies flowing one way.
  • Give each service a single responsibility. Extract shared logic into its own component.
  • Communicate "upwards" with events (ApplicationEventPublisher) instead of direct references.
  • Depend on interfaces.
  • Use constructor injection everywhere, so cycles fail fast at startup instead of hiding.
  • Enforce the rules with ArchUnit tests, or Spring Modulith.

Common trap: "switch to setter or field injection". That hides the cycle, and doesn't even work on Spring Boot 2.6+ unless you opt back into circular references.

Follow-up questions this topic invites — and their answers

Q: What's the difference between JDK dynamic proxies and CGLIB proxies? A: JDK proxies implement the bean's interfaces, so callers must use the interface type. CGLIB creates a subclass of the bean class, so it works without interfaces, but can't intercept final methods. Spring Boot defaults to CGLIB (proxyTargetClass=true).

Q: How do you order several aspects on the same method? A: Annotate the aspect classes with @Order (or implement Ordered). A lower value means higher precedence: it runs first on the way in, and last on the way out.

Q: Where should a Spring Batch job's state live? A: In the job repository, the BATCH_* tables in a real database. That lets a failed job restart from its last committed chunk. An in-memory repository loses the progress.

Q: What's the difference between AspectJ and Spring AOP? A: Spring AOP is proxy-based: method execution on Spring beans only, woven at runtime. AspectJ weaves bytecode (at compile or load time), so it can intercept constructors, field access, private methods and self-calls, at the cost of more build and runtime setup.

Previous

Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions

Next

Spring Boot Internals & Auto-Configuration — Interview Questions

AI Tutor

Lesson: Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.