Spring Programming Questions & Answers

Explore model answers categorized by subjects like Java, HTML, DBMS, and more.

Spring Programming Questions & Answers

Define the AOP terminology?

Answer:
Many terms used to define the AOP (Aspect Oriented Programming) features and they are part of the AOP language. These terms must be known to understand the AOP:
  * Aspect : An aspect is the cross-cutting functionality you are implementing. It is the aspect, or area of your application you are modularizing. The most common example of aspect is logging. Logging is something that is required throughout an application.
  * Joinpoint : A joinpoint is a point in the execution of the application where an aspect can be plugged in.
  * Advice : Advice is the actual implementation of our aspect. It is advising your application of new behaviour.
  * Pointcut : A pointcut defines at what joinpoints advice should be applied.
  * Introduction : An introduction allows you to add new methods or attributes to existing classes.
  * Target : A target is the class that is being advised.
  * Proxy : A proxy is the object created after applying advice to the target object.
  * Weawing : Weawing is the process of applying aspects to a target object to create a new proxied object.

Explain the Weaving process in Spring framework?

Answer:
Weaving is the process of applying aspects to a to a target object to create a new proxied object. The aspects are woven into the target object at the specified joinpoints. The weaving can take place at several points in the target class's lifetime:
  * Compile time : Aspects are woven in when the target class is compiled. This requires a special compiler.
  * Classload time : Aspects are woven at the time of loading of the target class into the JVM. It is done by ClassLoader that enhances that target class's bytecode before the class is introduced into the application.
  * Runtime : Sometimes aspects are woven in during the execution of the applicaion. 

Name the interfaces that are used to create an Advice in Spring framework?

Answer:
The interfaces that are used to create an Advice are:
  * org.aopalliance.intercept.MethodInterceptor
  * org.springframework.aop.BeforeAdvice
  * org.springframework.aop.AfterReturningAdvice
  * org.springframework.aop.ThrowsAdvice

Explian the Before advice?

Answer:
Before the purchasing of our customer, we want to give them a warm greeting. For this, we need to add functionality before the method buySquishee() is executed. To accomplish this, we extend the MethodBeforeAdvice interface:
  public interface MethodBeforeAdvice{
    void before(Method m, Object[] args, Object target) throws Throwable
  }
This interface provides access to the target method, the arguments passed to this method, and the target object of the method invocation.

Explain the After returning advice?

Answer:
We want to make sure that we thank our patrons after they make their purchase. To do this, we implement AfterReturningAdvice:
  public interface AfterReturningAdvice{
    void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable
    }
  } 

Like MethodBeforeAdvice, this advice gives you access to the method that was called, the arguments that were passed, and the target object.

Explain the Around advice?

Answer:
The MethodInterceptor provides the ability to do both before advice and after advice in one advice object:
  public interface MethodInterceptor{
  Object invoke(MethodInvocation invocation) throws Throwable;
}

There are two important difference between MethodInterceptor and the both before and after advice. First, the method interceptor implementation controls the target method invocation, and this invocation done by calling MethodInvocation.proceed(). Second, MethodInterceptor gives you control over what object is returned.

Explain the Regular expression pointcuts?

Answer:
The RegexpMethodPointcut lets you leverage the power of regular expressions to define your pointcuts. It uses Perl-style regular expressions to define the pattern that should match your intended methods.
Common regular expression symbol used are (.) matches any single character, (+) Matches the preceding character one or more times, (*) matches the preceding character zero or more, (\) Escapes any regular expression symbol.
For Example:
If we want to match all the setXxx methods, we need to use the pattern .*set.* (the first wildcard will match any preceding class name.

How will you create Introductions in Spring?

Answer:
The Introductions are little different from Spring advice. Advice are woven at different jointpoints surrounding a method invocation. Introductions affect an entire class by adding new methods and attributes to the adviced class.
Introductions allow you to build composite objects dynamically, affording you the same benefits as multiple inheritance.
Introductions are implemented through IntroductionMethodInterceptor, a subinterface of MethodInterceptor. This method adds one method:
  boolean implementsInterface(Class intf);
This method returns true if the IntroductionMethodInterceptor is responsible for implementing the given interface.

What is ProxyFactoryBean? Describe its properties?

Answer:
ProxyFactoryBean creates proxied objects. Like other JavaBeans, it has properties that control its behaviour. ProxyFactoryBean properties are:
  * target : The target bean of the proxy.
  * proxyInterface : A list of interfaces that should be implemented by the proxy.
  * interceptorNames : The bean names of the advice to be applied to the target.
  * singleton : Whether the factory should return the same instance of the proxy for each getBean invocation.
  * aopProxyFactory : The implemetation of the ProxyFactoryBean interface to be used.
  * exposeProxy : Whether the target class should have access to the current proxy. This is done by calling AopContext.getCurrentProxy.
  * frozen : Whether changes can be made to the proxy's advice once the factory is created.
  * optimize : Whether to aggressively optimize generated proxies.
  * proxyTargetClass : Whether to proxy the target class, rather than implementing an interface.

What is Autoproxying in Spring?

Answer:
Spring has a facility of autoproxy that enables the container to generate proxies for us. We create autoproxy creator beans. Spring provides two classes to support this:
  * BeanNameAutoProxyCreator
  * DefaultAdvisorAutoProxyCreator

Explain BeanNameAutoProxyCreator and DefaultAdvisorAutoProxyCreator classes?

Answer:
BeanNameAutoProxyCreator generates proxies for beans that match a set of names. This name matching is similar to the NameMethodMatcherPointcut which allows for wildcard matching on both ends of the name. This is used to apply an aspect or a group of aspects uniformly across a set of beans that follow a similar naming conventions.
The DefaultAdvisorAutoProxyCreator is the more powerful autoproxy creator. Use this class to include it as a bean in your BeanFactory configuration. It implemnts the BeanPostProcessor interface. DefaultAdvisorAutoProxyCreator only works with advisors.

What is Metadata autoproxying?

Answer:
Spring also supprts autoproxying driven by metadata. Metadata autoproxy configuration is determined by source level attributes and keeps AOP metadata with the source code that is being advised. This lets your code and configuration metadata in one place.
The most common use of metadata autoproxying is for declarative transaction support. 

Explain DAO in Spring framework?

Answer:
Spring Framework's Data Access Object (DAO) support provides integration of heterogeneous Java Database Connectivity (JDBC) and Object-Relational Mapping (ORM) products. DAO support is provided for JDBC, Hibernate, iBATIS, Java Data Objects (JDO), Java Persistence API (JPA), Oracle's TopLink and Common Client Interface (CCI). 

Explain the Spring's DataAccessException?

Answer:
Spring's org.springframework.dao.DataAccessException extends the extends NestedRuntimeException which in turn extends and RuntimeException. Hence DataAcccessException is a RuntimeException so there is no need to declare it in the method signature.

List the Springs's DAO exception hierarchy?

Answer:
Springs's DAO exception hierarchy is :
  * CleanupFailureAccessException
  * DataAccessResourceFailureException
  * DataIntegrityViolationException
  * DataRetrievalFailureException
  * DeadlockLoserDataAccessException
  * IncorrectUpdateSemanticsDataAccessException
  * InvalidDataAccessApiUsageException
  * InvalidDataAccessResourceUsageException
  * OptimisticLockingFailureException
  * TypeMismatchDataAccessException
  * UncategorizedDataAccessException

What is JdbcTemplate class used for in Spring's JDBC API?

Answer:
The JdbcTemplate class is the central class in the JDBC core package. It simplifies the use of JDBC since it handles the creation and release of resources. This class executes SQL queries, update statements or stored procedure calls, imitating iteration over ResultSets and extraction of returned parameter values. It also catches JDBC exceptions defined in the hierarchy of org.springframework.dao package. Code using the JdbcTemplate only need to implement callback interfaces, giving them a clearly defined contract. 
The PreparedStatementCreator callback interface creates a prepared statement given a Connection provided by this class, providing SQL and any necessary parameters. The JdbcTemplate can be used within a DAO implementation via direct instantiation with a DataSource  reference, or be configured in a Spring IOC container and given to DAOs as a bean reference.
Example:

JdbcTemplate  template = new JdbcTemplate(myDataSource);
A simple DAO class looks like this.
public class StudentDaoJdbc implements StudentDao {
          private JdbcTemplate jdbcTemplate;

     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
          this.jdbcTemplate = jdbcTemplate;
     }
    // more code here
} 

What is NamedParameterJdbcTemplate class used for in Spring's JDBC API?

Answer:
The NamedParameterJdbcTemplate class adds support for programming JDBC statements using named parameters (as opposed to programming JDBC statements using only classic placeholder ('?') arguments. The NamedParameterJdbcTemplate class wraps a JdbcTemplate, and delegates to the wrapped JdbcTemplate to do much of its work.

Name the JDBC Core classes to control basic JDBC processing and error handling in Spring's JDBC API?

Answer:
the JDBC Core classes to control basic JDBC processing and error handling in Spring's JDBC API are :
  * JdbcTemplate
  * NamedParameterJdbcTemplate
  * SimpleJdbcTemplate (Java5)
  * DataSource
  * SQLExceptionTranslator

What classes are used to Control the database connection in Spring's JDBC API?

Answer:
The classes that are used to Control the database connection in Spring's JDBC API are :
  * DataSourceUtils
  * SmartDataSource 
  * AbstractDataSource
  * SingleConnectionDataSource
  * DriverManagerDataSource
  * TransactionAwareDataSourceProxy 
  * DataSourceTransactionManager

How does Spring supports DAO in hibernate?

Answer:
Spring’s HibernateDaoSupport class is a convenient super class for Hibernate DAOs. It has handy methods you can call to get a Hibernate Session, or a SessionFactory. The most convenient method is getHibernateTemplate(), which returns a HibernateTemplate. This template wraps Hibernate checked exceptions with runtime exceptions, allowing your DAO interfaces to be Hibernate exception-free.

How do you configure your database driver in spring?

Answer:
To configure your database driver using datasource "org.springframework.jdbc.datasource.DriverManagerDataSource". For Example:
 

    
        org.hsqldb.jdbcDriver
    
    
        jdbc:hsqldb:db/appfuse
    
    sa
    

 

How can you configure JNDI instead of datasource in spring applicationcontext.xml?

Answer:
You can configure JNDI instead of datasource in spring applicationcontext.xml using "org.springframework.jndi.JndiObjectFactoryBean". For Example:
 

    
        java:comp/env/jdbc/appfuse
    

How can you create a DataSource connection pool?

Answer:
To create a DataSource connection pool :
  
       
               ${db.driver}
       
       
              ${db.url}
       
       
             ${db.username}
       
       
            ${db.password}
       
 

Explain about BatchPreparedStatementSetter?

Answer:
BatchPreparedStatementSetter interface sets values on a PreparedStatement provided by the JdbcTemplate class for each of a number of updates in a batch using the same SQL. Implementations are responsible for setting any necessary parameters. SQL with placeholders will already have been supplied. Implementations of BatchPreparedStatementSetter do not need to concern themselves with SQLExceptions that may be thrown from operations they attempt. The JdbcTemplate class will catch and handle SQLExceptions appropriately. 
BatchPreparedStatementSetter has two method:

  * int getBatchSize() :-  Return the size of the batch.
  * void setValues(PreparedStatement ps, int i) :-Set values on the given PreparedStatement.

Explain about RowCallbackHandler and why it is used?

Answer:
RowCallbackHandler interface is used by JdbcTemplate for processing rows of a ResultSet on a per-row basis. Implementations of this interface perform the actual work of processing each row but don't need to worry about exception handling. SQLExceptions will be caught and handled by the calling JdbcTemplate. RowCallbackHandler object is typically stateful: It keeps the result state within the object, to be available for later inspection.
RowCallbackHandler interface has one method :

   void processRow(ResultSet rs) :- Implementations must implement this method to process each row of data in the ResultSet.

What is Spring Framework?

Answer:

What is Spring Framework?

  • Spring is an open-source framework, created by Rod Johnson in 2003, designed to simplify enterprise Java development.
  • It was introduced as a lightweight alternative to J2EE/EJB, addressing the complexity, heavy configuration, and tight coupling that plagued traditional enterprise apps.

Key Characteristics

  1. Lightweight Container
    • Spring provides an IoC (Inversion of Control) container that manages the lifecycle and configuration of application objects (beans).
    • Unlike EJB, it works with plain old Java objects (POJOs), making apps easier to test and reuse.
  2. Loose Coupling via Dependency Injection (DI)
    • Dependencies are injected into beans rather than beans creating their own dependencies, leading to more maintainable and testable code.
  3. Modular & Flexible
    • You can use only the parts you need (core container, data access, transaction management, web, security, etc.) without dragging in the whole framework.
  4. Integration-Friendly
    • Provides wrappers and templates to easily integrate with databases (JDBC, JPA, Hibernate), messaging systems, and other frameworks.
  5. Testability
    • Because components are POJOs, they are easy to test in isolation without needing a heavy server container.

Spring for Web & Services

  • Spring MVC ? A web framework built on top of Spring for building web applications with clear separation of concerns (Controller, Service, DAO layers).
  • Spring Web Services (Spring-WS) ? Designed for contract-first SOAP services, making it easier to build flexible, document-driven web services.
  • Today, Spring also powers RESTful APIs and microservices through Spring Boot + Spring Cloud.

In summary:
Spring is a lightweight, open-source, enterprise-grade framework that simplifies Java development by promoting loose coupling, modularity, testability, and integration. While originally created as an alternative to EJBs, it has evolved into the most popular Java ecosystem, supporting everything from simple applications to cloud-native microservices.

What are the various modules of Spring?

Answer:

Spring Framework Modules

The Spring Framework is organized into modules, each providing specific functionality. Together, they make Spring flexible, lightweight, and suitable for enterprise applications.

1. Core Container

  • The foundation of the framework.
  • Provides Inversion of Control (IoC) and Dependency Injection (DI).
  • Manages bean creation, configuration, and lifecycle.

2. Application Context Module

  • Builds on the core container.
  • Provides advanced features: internationalization (i18n), event propagation, resource loading.
  • Also manages enterprise services such as JNDI, EJB integration, mail, scheduling.

3. Spring AOP (Aspect-Oriented Programming) Module

  • Allows separation of cross-cutting concerns (logging, transactions, security, etc.) from business logic.
  • Provides declarative transaction management.

4. JDBC Abstraction & DAO Module

  • Simplifies database access by removing boilerplate JDBC code.
  • Provides consistent exception handling.
  • Supports declarative transaction management with Spring’s AOP.

5. ORM (Object-Relational Mapping) Module

  • Integration with popular ORM frameworks like Hibernate, JPA, iBatis/MyBatis, JDO.
  • Simplifies persistence and transaction management.

6. Web Module

  • Provides basic web-oriented integration features.
  • Includes multipart request handling, and integration with other web frameworks.

7. Spring MVC Module

  • A full Model-View-Controller web framework.
  • Provides clear separation of concerns between controller, model (business logic), and view.
  • Supports RESTful web services and flexible view technologies (JSP, Thymeleaf, FreeMarker, etc.).

Summary for interviews:
Spring is made up of seven key modules, all built on top of the core container. These modules (Core, Context, AOP, JDBC/DAO, ORM, Web, and MVC) give developers a complete toolkit to build scalable, enterprise-ready, testable applications.

Explain the IoC (Inversion of Control) in Spring framework?

Answer:

Inversion of Control (IoC) in Spring

  • Inversion of Control (IoC) is the core principle of the Spring Framework.
  • Instead of the application code creating and managing objects, the Spring IoC container takes over that responsibility.
  • The IoC container is primarily represented by the org.springframework.beans and org.springframework.context packages.

How IoC Works

  1. Developer’s role ? Define beans and their dependencies (in XML, Java annotations, or Java configuration).
  2. Spring’s role ?
    • Creates the objects (beans).
    • Wires them together (dependency injection).
    • Manages their lifecycle (initialization, destruction).

This way, application code focuses only on business logic, not on wiring and managing dependencies.

Dependency Injection (DI) – IoC Implementation in Spring

Spring uses Dependency Injection (DI) to achieve IoC.

There are two main types:

  1. Setter Injection
    • Dependencies are injected via JavaBean setter methods.
    • Flexible, allows optional dependencies.
    • Example:

      @Component class Student {    private Address address;    @Autowired    public void setAddress(Address address) {        this.address = address;    } }

  2. Constructor Injection
    • Dependencies are injected via constructor arguments.
    • Ensures all required dependencies are available at object creation.
    • Recommended as a best practice in Spring Boot.
    • Example:

      @Component class Student {    private final Address address;    @Autowired    public Student(Address address) {        this.address = address;    } }

Summary (interview answer):
In Spring, IoC means the container, not the application code, is responsible for creating and managing objects. This is achieved through Dependency Injection, which can be done via constructor injection or setter injection. Constructor injection is preferred for mandatory dependencies, while setter injection is useful for optional ones.

What is (AOP) aspect-oriented programming?

Answer:

Aspect-Oriented Programming (AOP) in Spring

  • Definition:Aspect-Oriented Programming (AOP) is a programming paradigm that allows the modularization of cross-cutting concerns — functionality that cuts across multiple modules (e.g., logging, security, transaction management).
     
  • Why needed?
    In Object-Oriented Programming (OOP), concerns like logging or security often get scattered across many classes, leading to code duplication and tight coupling.
    AOP extracts these concerns into aspects, keeping the core business logic clean.

Core AOP Concepts in Spring

  1. Aspect : A module that encapsulates a cross-cutting concern (e.g., a logging aspect).
  2. Join Point : A point in program execution (like method call, object creation) where an aspect can be applied.
  3. Advice : Action taken by an aspect at a particular join point. Types:
    • @Before : runs before method execution.
    • @After : runs after method execution.
    • @Around : wraps method execution (before + after).
    • @AfterReturning, @AfterThrowing : on successful/exceptional return.
  4. Pointcut : An expression that selects specific join points (e.g., methods in a package).
  5. Weaving : Linking aspects with target objects to create advised objects (at runtime in Spring).

AOP in Spring Framework

Spring uses AOP in two major ways:

  1. Declarative Enterprise Services
    • Most commonly used for transaction management.
    • Example: @Transactional annotation leverages AOP proxies to handle transaction boundaries without cluttering business logic.
  2. Custom Aspects
    • Developers can define their own aspects for logging, security checks, performance monitoring, etc.

      Example:

      @Aspect 

      @Component 

      public class LoggingAspect {        

      @Before("execution(* com.example.service.*.*(..))")    

      public void logBefore(JoinPoint joinPoint) {        

      System.out.println("Executing: " + joinPoint.getSignature());   

       }

      }

Summary (Interview Style)

AOP in Spring is used to separate cross-cutting concerns (like transactions, logging, security) from business logic.
It provides aspects that modularize these concerns and uses proxies + weaving at runtime to apply them declaratively.
The most important built-in service is declarative transaction management, but developers can also create custom aspects to complement OOP with AOP.

What are the various approaches use by IoC pattern for decoupling of component in Spring framework?

Answer:

IoC (Inversion of Control) Injection Approaches

The IoC principle decouples object creation and dependency management from application logic.
In practice, Dependency Injection (DI) is the technique Spring uses to achieve IoC.

There are three main approaches:

1. Interface Injection (least common, not used in Spring)

  • The dependency provides an injection method that the client class must implement.
  • The container then calls this method to inject the dependency.
  • Leads to tight coupling, since classes must implement framework-specific interfaces.
  • Example (conceptual):

    interface ServiceAware {    
    void setService(Service service); 

    class Client implements ServiceAware {    
    private Service service;    
    public void setService(Service service) { this.service = service; } }

  • Rarely used; Spring avoids this to keep beans as POJOs (Plain Old Java Objects).

2. Setter Injection (supported in Spring)

  • Dependencies are injected via public setter methods.
  • Flexible ? allows optional or changeable dependencies.
  • Example:

    @Component class Student {    
    private Address address;    

    @Autowired    
    public void setAddress(Address address) {        
    this.address = address;    
    } }

  •  Good for optional dependencies, but makes objects mutable.

3. Constructor Injection (preferred in Spring Boot)

  • Dependencies are injected via the constructor at object creation.
  • Ensures all required dependencies are available immediately.
  • Promotes immutability and makes testing easier.
  • Example:

    @Component class Student {   
     private final Address address;    

    @Autowired    
    public Student(Address address) {        
    this.address = address;    
    } }

  •  Best practice for mandatory dependencies.

Comparison

ApproachSpring SupportProsCons
Interface Injection(not supported)Explicit contract, clarityCouples code to framework, verbose
Setter InjectionYesFlexible, good for optional depsObject mutable, dependency not guaranteed
Constructor InjectionYesImmutable, mandatory deps enforced, test-friendlyComplex with too many parameters

Summary (Interview Answer):
The IoC pattern can use interface injection, setter injection, or constructor injection. Spring avoids interface injection (to keep beans as POJOs), but supports setter and constructor injection. Constructor injection is preferred for mandatory dependencies, while setter injection is best for optional ones.

Compare Spring with Enterprise Java Beans?

Answer:
As J2EE containers, both Spring and EJB offer the developer powerful features for developing applications. Comparing the features:
 
Transaction management : EJB must use a JTA transaction manager and supports transactions that span remote method calls. Spring supports multiple transaction environment with JTA, Hibernate, JDO, JDBC, etc and does not support distributed transaction.

Declarative Transaction support : EJB can define transaction in deployment descriptor and can\'t derivatively define rollback behavior. Spring can define transaction in Spring configuration file and can declaratively define rollback behaviour per method and per exception type.

Persistence : EJB supports programmatic bean-managed persistence and declarative container managed persistence. Spring provides a framework for integrating with several persistence technologies, including JDBC, Hibernate, JDO, and iBATIS.

Declarative security : EJB supports declarative security through users and roles and configured in the deployment descriptor. In Spring, no security implementation out of the box. Acegi provides the declarative security framework built on the top of Spring.

Distributed computing : EJB provides container managed remote method calls. Spring provides proxying for remote calls via RMI, JAX-RPC, and web services.

What is BeanFactory in Spring framework?

Answer:
A BeanFactory is an implementation fo the factory design patterns. The BeanFactory is a root interface for accessing a Spring bean container. This is the basic client view of a bean container; further interfaces such as ListableBeanFactory and ConfigurableBeanFactory are available for specific purposes. 

This interface is implemented by objects that hold a number of bean definitions, each uniquely identified by a String name. Depending on the bean definition, the factory will return either an independent instance of a contained object.

The point of this approach is that the BeanFactory is a central registry of application components, and centralizes configuration of application components (no more do individual objects need to read properties files.
There are several implementations of BeanFactory in Spring. But the most useful is


org.springframework.beans.factory.xml.XmlBeanFactory, which loads its bean based on the definitions contained in an XML file.

BeanFactory f = new XmlBeanFactory(new FileInputStream(\"beans.xml\"));

Explain the Spring Bean lifecycle?

Answer:

Spring Bean Lifecycle

When a bean is created in the Spring Container, it goes through a series of steps before being ready for use, and again when it’s destroyed.

1. Bean Instantiation

  • Spring creates an instance of the bean (using constructor or factory method).

2. Dependency Injection (DI)

  • Spring sets bean properties (via setters, constructor args, or autowiring).

3. Aware Interfaces (optional)

  • If the bean implements special Aware interfaces:
    • BeanNameAware ? gets the bean’s name.
    • BeanFactoryAware ? gets access to BeanFactory.
    • ApplicationContextAware ? gets ApplicationContext.

4. BeanPostProcessor (Before Initialization)

  • Any registered BeanPostProcessor executes postProcessBeforeInitialization().

5. Initialization

  • Possible init options:
    • @PostConstruct (annotation-based)
    • InitializingBean.afterPropertiesSet() (interface-based)
    • Custom init method (init-method in XML or @Bean(initMethod=...) in Java config)

6. BeanPostProcessor (After Initialization)

  • postProcessAfterInitialization() runs.

Bean is now ready to use in the application.

7. Destruction (on context shutdown)

  • Possible destroy options:
    • @PreDestroy (annotation-based)
    • DisposableBean.destroy() (interface-based)
    • Custom destroy method (destroy-method in XML or @Bean(destroyMethod=...) in Java config)

Extension Points

  • BeanPostProcessor ? customize beans before/after initialization.
  • InitializingBean / @PostConstruct ? hook for init logic.
  • DisposableBean / @PreDestroy ? hook for cleanup logic.

Full Lifecycle Sequence

Instantiate 

  1. DI (set properties)  -Aware Interfaces (BeanNameAware, BeanFactoryAware, etc.) 
  2.  BeanPostProcessor (before init) 
  3.  @PostConstruct / afterPropertiesSet() / custom init 
  4.  BeanPostProcessor (after init) 
  5. === Bean Ready === @PreDestroy / destroy() / custom destroy

Singleton bean in Spring vs Singleton Design Pattern?

Answer:

1. GoF Singleton (Design Pattern)-Gang of Four (GOF) Design Patterns

  • Definition: A class ensures only one instance exists across the entire JVM and provides a global point of access.
  • Scope: JVM-wide.
  • Implementation: Usually done with:
    • Private constructor
    • A static field holding the single instance
    • A static getInstance() method
  • Example:

    public class Singleton {    private static final Singleton INSTANCE = new Singleton();    private Singleton() {}    public static Singleton getInstance() {        return INSTANCE;    } }

  • Use case: Global state, shared resources like logging, configuration, etc.

2. Spring "Singleton" Bean Scope

  • Definition: Spring creates one instance of the bean per Spring ApplicationContext.
  • Scope: Container-wide, not JVM-wide.
  • Implication:
    • If you have multiple Spring contexts in one JVM, each will have its own singleton bean instance.
    • Different from GoF singleton, since it’s not truly JVM-wide.
  • Implementation:
    • Mark a bean with @Scope("singleton") (default scope).
    • Spring ensures only one instance of that bean exists per context, but doesn’t prevent multiple contexts from creating their own.
  • Example:

    @Component @Scope("singleton")  // default, can be omitted public class MyService {}

  • Use case: Service components, DAOs, etc., where a shared instance per context is enough.

Key Differences

AspectGoF SingletonSpring Singleton
ScopeJVM-widePer Spring container
ControlClass controls instantiationSpring IoC container controls instantiation
Multiple instances?Never (per JVM)Yes, if multiple contexts exist
ImplementationPrivate constructor + static instancePlain POJO + managed by Spring

Conclusion:

  • A Spring singleton is a container-level singleton.
  • A GoF singleton is a JVM-level singleton.
  • They sound the same but operate at different scopes.

Note:- If you put a GoF singleton inside Spring, it will still be one instance per JVM, regardless of how many Spring contexts exist.

DI vs IoC ?

Answer:

IoC vs DI 

  • IoC (Inversion of Control): A general principle where the framework, not the developer, controls object creation and lifecycle.
  • DI (Dependency Injection): A specific type of IoC where the framework provides an object’s dependencies (via constructor, setter, or field injection).
     

So, all DI is IoC, but not all IoC is DI.

How does Spring resolve circular dependencies?

Answer:

We can resolve circular dependecies 

  • By creating proxies/early references using singleton factory beans.
  • Works for setter injection, not for constructor injection.
     Fix: use @Lazy, redesign dependencies, or use constructor injection with refactoring.

Why Spring Uses Proxies/Early References

  • Spring’s default singleton scope means one instance per container.
  • During bean creation, if Bean A depends on Bean B, and Bean B depends on Bean A, you have a circular dependency.
  • To resolve this, Spring uses:
    • Singleton registry (singletonFactories) ? exposes an early reference (often a proxy) before the bean is fully initialized.
    • This works fine if dependencies are injected via setter injection or field injection, because the bean reference can be swapped later.

The Problem with Constructor Injection

  • With constructor injection, the dependency must be fully available at construction time.
  • If Bean A’s constructor needs Bean B, but Bean B’s constructor also needs Bean A ? Spring cannot create either without breaking the cycle.
  • Proxies/early references can’t help here, because the constructor expects the real instance at creation.

Fixes

  1. Use @Lazy

    • Delay the resolution of one side of the dependency until actually needed.

     

    @Component class A {    private final B b;    public A(@Lazy B b) { this.b = b; } }

  2. Redesign dependencies
    • Break the circular dependency (preferred).
    • Extract a common interface/service to avoid direct cyclic wiring.
       
  3. Constructor injection + refactor
    • Refactor so only one side uses constructor injection and the other uses setter/field injection (but generally constructor injection everywhere is best practice).

Summary

  • Singleton factory beans + early references ? solve circular dependencies only for setter/field injection.
  • Constructor injection circular deps ? cannot be resolved automatically, need @Lazy or redesign.

@Autowired vs @Inject vs @Resource?

Answer:

Best Practice (Spring Boot)

Use @Autowired (constructor injection, no @Autowired needed since Spring 4.3 if only one constructor).

  • Prefer constructor injection for immutability and testability.
  • Fall back to @Inject only if writing framework-agnostic code.
  • @Resource only for special cases (e.g., JNDI lookups or legacy compatibility).

Quick Interview Answer:

  • @Autowired = Spring, by type, required=false possible.
  • @Inject = JSR-330, by type, no required=false.
  • @Resource = JSR-250, by name first. 
  • In Spring Boot ? prefer @Autowired (constructor injection).

 1. @Autowired (Spring-specific)

  • From: Spring Framework
  • Resolution:
    • By type (primary strategy). 
    • If multiple beans match ? looks for @Qualifier or bean name. 
  • Attributes:
    • required = true by default ? if no bean found, context startup fails.
    • Can set required = false to make it optional. 
    • Works on constructor, setter, field.
       
  • Extra features:
     
    • Integrates tightly with Spring ecosystem (e.g., supports @Lazy, @Primary).
       
  • Options:
    • required=false ? makes dependency optional.
    • Can be combined with @Qualifier to resolve ambiguity by name.
       
  • Flexibility: Works with constructor, setter, and field injection.
  • Spring Boot: Preferred (better tooling, integrates smoothly with Boot’s auto-configuration).

@Autowired

private MyService myService;   // by type

2. @Inject (JSR-330, Java standard)

  • From: Java specification (javax.inject / jakarta.inject).
  • Resolution:
    • By type, same as @Autowired.
    • No required attribute ? absence of bean causes startup failure unless you wrap with Optional or Provider.
       
  • Advantage:
    • Portable, not tied to Spring ? works in other DI frameworks like Guice, CDI.
       
  • Disadvantage:
    • Lacks Spring’s advanced attributes (required, @Primary, etc.).

Origin: JSR-330 (javax.inject / jakarta.inject).

  • Injection typeBy type (like @Autowired).
  • Options:
    • No required=false.
    • Ambiguity resolved with @Named.
  • Benefit: Standard ? works across DI frameworks (Guice, Spring, CDI).

@Inject

  • private MyService myService;   // by type

3. @Resource (JSR-250, Java EE legacy)

  • From: Java EE / JSR-250 (javax.annotation).
  • Resolution order:
     
    • By name (bean name must match the field/setter name).
    • If not found ? fallback to by type.
       
  • Usage:
    • Typically on fields or setters (not constructors).
       
  • Disadvantage:
    • Less flexible, more brittle if bean names change.

Origin: JSR-250 (javax.annotation).

  • Injection typeBy name first, fallback to by type.
     
  • Options:
     
    • Uses @Resource(name="beanName") explicitly.
       
  • Typical use: Legacy EE integration (JNDI resources, datasources). 

@Resource(name = "myService")

  • private MyService myService;   // by name

Quick Comparison

AnnotationOriginResolutionAttributes / FlexibilityCommon Use
@AutowiredSpringBy type ? qualifier/name fallbackrequired, @Primary, @Lazy, works everywherePreferred in Spring Boot
@InjectJSR-330By typeStandard, no Spring extrasPortable code across DI frameworks
@ResourceJSR-250By name ? fallback to typeNo Spring features, name-sensitiveLegacy integration / Java EE style

 

 Best practice in Spring Boot: use @Autowired, preferably on constructors (no need to even put the annotation if there’s a single constructor).

What is autowiring in the Spring framework? Explain its type?

Answer:
You wire all of your bean's properties explicitly using the  element, However you can have Spring wire them automatically by setting the 'autowire' property on each  that you want autowired:
  

There are four types of autowiring:
  * byName :- Attempts to find a bean in the container whose name is the same as the name of the property being wired.
  * byType :- Attempts to find a single bean in the container whose type matches the type of the property being wired. If no matching bean is found, the property will not be wired.
  * constructor :- Tries to match up one or more beans in the container with the parameters of one of the constructors of the bean being wired.
  * autodetect :- Attempts to autowire by constructor first and then using byType. Ambiguity is handled the same way as with constructor and byType wiring.

What are the various custom editors provided by the Spring Framework?

Answer:
The various custom editors provided by the Spring Framework are:
  * PropertyEditor
  * URLEditor
  * ClassEditor
  * CustomDateEditor
  * FileEditor
  * LocaleEditor
  * StringArrayPropertyEditor
  * StringTrimmerEditor

Explain the Events and listener in Spring framework?

Answer:
All the Events are the subclasses of abstract class org.springframework.context.ApplicationEvent. These are:
  * ContextClosedEvent :- Published when the application context is closed.
  * ContextRefereshedEvent :- Published when the application context is initialized or refereshed.
  * RequestHandledEvent :- Published within a web application context when a request is handled.

If you want a bean to respond to application events, all you need to do is implement the org.springframework.context.ApplicationListener interface. This interface forces your bean to implement the onApplicationEvent() method, which is responsible for reaching to the application event:
  
  public class RefreshListener implements ApplicaitonListener{
  public void onApplicationEvent(ApplicationEvent e) {
    some code here// 
}

You need to register it within the context:

How to integrate your Struts application with Spring?

Answer:
We have two options that are available to integrate Struts application with Spring:
  * Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their dependencies in a Spring context file.
  * Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a getWebApplicationContext() method. 

What are ORM’s Spring supports ?

Answer:
Spring supports the following ORM’s :
  * Hibernate
  * iBatis
  * JPA (Java Persistence API)
  * TopLink
  * JDO (Java Data Objects)
  * OJB

What is an Advice in Spring framework?

Answer:
An Advice is a Spring bean. Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, and advice is inserted into an application at joinpoints. An advice instance can be shared across all advised objects, or unique to each advised object. This corresponds to per-class or per-instance  advice.
Advice types in Spring:
  * Interception around advice
  * Before advice
  * Throws advice
  * After Returning advice
  * Introduction advice

What is an Advisor API in Spring

Answer:
Advisor is an aspect that contains just a single advice object associated with a pointcut expression. A pointcut is something that defines at what joinpoints an advice should be applied. Advices can be applied at any joinpoint that is supported by the AOP framework. These Pointcuts allow you to specify where the advice can be applied. 
Any advisor can be used with any advice. The org.springframework.aop.support.DefaultPointcutAdvisor  is the most commonly used advisor class. For example, it can be used with a MethodInterceptor, BeforeAdvice or ThrowsAdvice.

Define a Pointcut in Spring?

Answer:
Spring defines pointcuts in terms of the class and method that is being advised. Advice is woven into the target class and its methods are based on their characteristics, such as class name and method signature. The core interface for Spring's pointcut framework is, naturally, the Pointcut interface.