Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 77 ยท Java Interview Questions

Spring and Spring Boot: IoC, Beans, Auto-Configuration and JPA

Answer Spring Boot interview questions on IoC, bean scopes, auto-configuration, @Transactional proxies and JPA, with runnable stand-ins in plain Java.

Spring interviews follow a predictable arc. They start with "What is inversion of control?" and "What does @SpringBootApplication do?", move on to bean scopes and auto-configuration, and end with the questions that separate people who use Spring from people who understand it: why does @Transactional sometimes do nothing, and why does this query run a hundred times?

The site cannot run Spring itself (no Maven dependencies, no web server), so every real Spring snippet below is read-only. To make the answers concrete, the runnable examples are small stand-ins written in plain Java 25 that implement the same ideas: a dependency-injection container, a dynamic proxy that adds transactions, and a conditional auto-configuration. They show why Spring behaves as it does. For the full lessons, see Spring Boot and the Advanced Java track, and for the language basics behind them, Java OOP Core Questions.

What Spring really does

Creates objects The container builds your beans.
Wires them Dependencies are injected.
Wraps them Proxies add transactions and security.
Configures itself Boot adds sensible defaults.

Most interview questions are one of these four ideas.

1 / 2

What is inversion of control and dependency injection?

Short answer: In normal code an object creates the things it needs (new EmailSender()). With inversion of control (IoC) the framework creates and connects the objects, and your class only declares what it needs. Dependency injection (DI) is how those needs are supplied: through a constructor, a setter, or a field.

The benefits are testability (pass in a fake sender), loose coupling (depend on an interface, not an implementation), and central configuration. Prefer constructor injection: dependencies are final, the object can never exist half-built, and a missing bean fails at startup. Field injection with @Autowired hides dependencies and makes unit tests awkward. In Spring, the ApplicationContext is the container: it reads configuration (annotations or Java @Configuration classes), creates beans, injects them, and manages their lifecycle.

The next program is a 40-line container with the same core behaviour: it scans a list of component classes, finds a constructor, and builds each dependency first.

Java A tiny dependency-injection container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Spring adds much more (scopes, lifecycle callbacks, circular-dependency handling, qualifiers), but this is the heart of it. Note the failure: a missing dependency is caught when the bean is built, not later in production. In Spring, if two beans fit the same type, you resolve it with @Qualifier or mark one @Primary.

What are bean scopes and the bean lifecycle?

Short answer: The scope decides how many instances exist. singleton (the default) is one per container; prototype creates a new instance each time it is requested; web scopes request and session live as long as an HTTP request or session. Singletons are shared by all threads, so they must be stateless or thread-safe: never keep per-request data in a field of a singleton.

The lifecycle is: instantiate, inject dependencies, run @PostConstruct or InitializingBean, the bean is ready, then at shutdown run @PreDestroy. A common trap is injecting a prototype into a singleton: the singleton gets one prototype at creation and keeps it. Use ObjectProvider<T> to ask for a fresh one each time.

What does @SpringBootApplication do?

Short answer: It is a shortcut for three annotations:

  • @Configuration: the class can declare beans.
  • @ComponentScan: scan this package and its sub-packages for @Component, @Service, @Repository, @Controller.
  • @EnableAutoConfiguration: let Boot configure beans based on the classpath and properties.
Java
// Read-only: the standard Spring Boot entry point
@SpringBootApplication
public class ShopApplication {
    public static void main(String[] args) {
        SpringApplication.run(ShopApplication.class, args);
    }
}

Because component scanning starts at the annotated class's package, put it in the root package of your project, or beans in sibling packages are not found. Starters such as spring-boot-starter-web are dependency bundles: adding one puts the right libraries on the classpath, which is what auto-configuration reacts to.

How does auto-configuration work?

Short answer: Boot ships hundreds of configuration classes guarded by conditions. Each says "create this bean only if...": @ConditionalOnClass (a library is on the classpath), @ConditionalOnMissingBean (you have not defined your own), @ConditionalOnProperty (a setting is on). That is why Boot "just works" by default and steps aside the moment you define your own bean. To see what was applied, run with --debug to print the conditions evaluation report.

Java Auto-configuration as conditional bean registration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Why does @Transactional sometimes not work?

Short answer: Spring implements @Transactional with a proxy: it wraps your bean in an object that begins a transaction, calls your method, then commits (or rolls back on a runtime exception). Anything that bypasses the proxy bypasses the transaction. The classic cases are self-invocation (a method calling another method of the same class through this), private or final methods that a proxy cannot override, calling a bean that was created with new rather than by the container, and checked exceptions, which do not trigger rollback unless you configure rollbackFor.

The stand-in below uses a JDK dynamic proxy to add transaction behaviour around methods marked @Transactional, and then demonstrates self-invocation.

Java A transaction proxy, and the self-invocation trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Run it and read the output: placeTwice shows a single BEGIN and COMMIT, because the two inner calls to place went straight to the object and never passed through the proxy. If the inner method needed a separate transaction (REQUIRES_NEW), it would silently not get one. The fix is to move the inner method to another bean, or restructure so the call crosses a bean boundary.

JPA and Hibernate: what do interviewers ask?

Short answer: JPA is the specification (@Entity, EntityManager, JPQL); Hibernate is the most common implementation; Spring Data JPA generates repository implementations from interfaces like interface UserRepository extends JpaRepository<User, Long>.

Know these four points:

  • Entity states: transient (new, not tracked), managed (tracked by the persistence context, changes are saved automatically at flush), detached (was managed, session closed), removed.
  • LAZY versus EAGER: associations should default to LAZY; EAGER loads related data on every query. Accessing a lazy association after the session closes causes LazyInitializationException.
  • The N+1 problem: loading 100 orders and then touching each order's customer runs one query for the orders and 100 for the customers. Fix it with JOIN FETCH, an entity graph, or batch fetching.
  • Open Session in View keeps the session open during the web request; it hides lazy-loading problems but can run queries from the view layer, so many teams switch it off.
Java
// Read-only: the N+1 trap and its fix
@Entity class Order {
    @Id Long id;
    @ManyToOne(fetch = FetchType.LAZY) Customer customer;
}

interface OrderRepository extends JpaRepository<Order, Long> {
    @Query("select o from Order o join fetch o.customer")   // one query, no N+1
    List<Order> findAllWithCustomer();
}

Quick answers for the follow-ups

  • @Component, @Service, @Repository, @Controller: all are stereotypes (specializations of @Component); @Repository also translates persistence exceptions; @RestController is @Controller + @ResponseBody.
  • Profiles: application-dev.properties plus spring.profiles.active=dev select environment-specific settings.
  • Actuator: production endpoints for health, metrics and info (/actuator/health); secure them.
  • Request flow: the DispatcherServlet receives the request, finds a handler method, converts input, calls your controller, and renders the response (JSON via message converters).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which injection style does Spring recommend, and why?

    Constructor injection makes dependencies explicit and immutable, fails fast at startup and makes unit tests simple.
  2. 2. What is the default bean scope?

    By default there is one shared instance per container, so beans should be stateless or thread-safe.
  3. 3. A @Transactional method is called from another method of the same class. Why might no transaction start?

    Transactions are added by a proxy around the bean. A call made via this bypasses the proxy, so the advice never runs.
  4. 4. What does @ConditionalOnMissingBean do?

    It is why Boot's defaults back off when you provide your own bean of that type.
  5. 5. Loading 100 orders and then reading each order's lazy customer runs how many queries?

    One query loads the orders and one more per order loads the customer. JOIN FETCH or an entity graph solves it.

Summary

  • IoC means the container creates and wires objects; prefer constructor injection.
  • Singleton is the default scope, so beans must be stateless; prototype creates a new object per request.
  • @SpringBootApplication = @Configuration + @ComponentScan + @EnableAutoConfiguration; put it in the root package.
  • Auto-configuration is conditional bean registration that backs off when you define your own bean.
  • @Transactional works through proxies, so self-invocation, private methods and new objects bypass it; checked exceptions do not roll back by default.
  • In JPA, keep associations lazy, fetch deliberately with JOIN FETCH, and watch for N+1 queries.

Next: C Pointers and Memory Questions, where the managed-language round gives way to systems programming.