Explore model answers categorized by subjects like Java, HTML, DBMS, and more.
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.
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.
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
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.
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.
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.
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.
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.
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.
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
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.
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.
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).
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.
Springs's DAO exception hierarchy is : * CleanupFailureAccessException * DataAccessResourceFailureException * DataIntegrityViolationException * DataRetrievalFailureException * DeadlockLoserDataAccessException * IncorrectUpdateSemanticsDataAccessException * InvalidDataAccessApiUsageException * InvalidDataAccessResourceUsageException * OptimisticLockingFailureException * TypeMismatchDataAccessException * UncategorizedDataAccessException
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
}
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.
the JDBC Core classes to control basic JDBC processing and error handling in Spring's JDBC API are : * JdbcTemplate * NamedParameterJdbcTemplate * SimpleJdbcTemplate (Java5) * DataSource * SQLExceptionTranslator
The classes that are used to Control the database connection in Spring's JDBC API are : * DataSourceUtils * SmartDataSource * AbstractDataSource * SingleConnectionDataSource * DriverManagerDataSource * TransactionAwareDataSourceProxy * DataSourceTransactionManager
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.
To configure your database driver using datasource "org.springframework.jdbc.datasource.DriverManagerDataSource". For Example:org.hsqldb.jdbcDriver jdbc:hsqldb:db/appfuse sa
You can configure JNDI instead of datasource in spring applicationcontext.xml using "org.springframework.jndi.JndiObjectFactoryBean". For Example:java:comp/env/jdbc/appfuse
To create a DataSource connection pool :${db.driver} ${db.url} ${db.username} ${db.password}
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.
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?
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.
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
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.
Inversion of Control (IoC) in Spring
This way, application code focuses only on business logic, not on wiring and managing dependencies.
Spring uses Dependency Injection (DI) to achieve IoC.
There are two main types:
Example:
@Component class Student { private Address address; @Autowired public void setAddress(Address address) { this.address = address; } }
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.
Aspect-Oriented Programming (AOP) in Spring
Spring uses AOP in two major ways:
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());
}
}
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.
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)
Example (conceptual):
interface ServiceAware {
void setService(Service service);
}
class Client implements ServiceAware {
private Service service;
public void setService(Service service) { this.service = service; } }
Example:
@Component class Student {
private Address address;
@Autowired
public void setAddress(Address address) {
this.address = address;
} }
Example:
@Component class Student {
private final Address address;
@Autowired
public Student(Address address) {
this.address = address;
} }
| Approach | Spring Support | Pros | Cons |
|---|---|---|---|
| Interface Injection | (not supported) | Explicit contract, clarity | Couples code to framework, verbose |
| Setter Injection | Yes | Flexible, good for optional deps | Object mutable, dependency not guaranteed |
| Constructor Injection | Yes | Immutable, mandatory deps enforced, test-friendly | Complex 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.
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.
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\"));
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
Instantiate
1. GoF Singleton (Design Pattern)-Gang of Four (GOF) Design Patterns
Example:
public class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton() {} public static Singleton getInstance() { return INSTANCE; } }
Example:
@Component @Scope("singleton") // default, can be omitted public class MyService {}
| Aspect | GoF Singleton | Spring Singleton |
|---|---|---|
| Scope | JVM-wide | Per Spring container |
| Control | Class controls instantiation | Spring IoC container controls instantiation |
| Multiple instances? | Never (per JVM) | Yes, if multiple contexts exist |
| Implementation | Private constructor + static instance | Plain POJO + managed by Spring |
Conclusion:
Note:- If you put a GoF singleton inside Spring, it will still be one instance per JVM, regardless of how many Spring contexts exist.
IoC vs DI
So, all DI is IoC, but not all IoC is DI.
We can resolve circular dependecies
Use @Lazy
@Component class A { private final B b; public A(@Lazy B b) { this.b = b; } }
Best Practice (Spring Boot)
Use @Autowired (constructor injection, no @Autowired needed since Spring 4.3 if only one constructor).
Quick Interview Answer:
@Autowired
private MyService myService; // by type
Origin: JSR-330 (javax.inject / jakarta.inject).
@Inject
Origin: JSR-250 (javax.annotation).
@Resource(name = "myService")
| Annotation | Origin | Resolution | Attributes / Flexibility | Common Use |
| @Autowired | Spring | By type ? qualifier/name fallback | required, @Primary, @Lazy, works everywhere | Preferred in Spring Boot |
| @Inject | JSR-330 | By type | Standard, no Spring extras | Portable code across DI frameworks |
| @Resource | JSR-250 | By name ? fallback to type | No Spring features, name-sensitive | Legacy 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).
You wire all of your bean's properties explicitly using theelement, 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.
The various custom editors provided by the Spring Framework are: * PropertyEditor * URLEditor * ClassEditor * CustomDateEditor * FileEditor * LocaleEditor * StringArrayPropertyEditor * StringTrimmerEditor
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:
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.
Spring supports the following ORM’s : * Hibernate * iBatis * JPA (Java Persistence API) * TopLink * JDO (Java Data Objects) * OJB
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
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.
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.