Spring Java Interview Questions | Eklavya Online

Spring Java Interview Questions

Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession( ) method.

public class HibernateUtil {

public static final ThreadLocal local = new ThreadLocal();

public static Session currentSession() throws HibernateException {

Session session = (Session) local.get();

//open a new session if this thread has no session

if(session == null) {

session = sessionFactory.openSession();

local.set(session);

}

return session;

}

}

It is also vital that you close your session after your unit of work completes. Note: Keep your Hibernate Session API handy. Quite often, hibernate is used with Spring framework, using the HibernateTemplate.

There are two ways to find it:

Using Classloader

Below code snippet can be used to find the location of java class

com.fromdev.MyClass
this.getClass().getClassLoader().getResource(“com/fromdev/MyClass.class”)

 

Using Protection Domain

We can use this to find the exact location a jar file containing the class JVM is using

clazz.getProtectionDomain().getCodeSource().getLocation()

How Java handles Two classes with same name in classpath

If I have two classes with same name say MyClass.java in two different jar in my classpath which one will be picked up by JVM , is there anyway I can suggest JVM to pick a specific one ?

Java interpreter loads classes based on the order they are specified in the CLASSPATH variable.
For example, lets say this is your classpath variable value

C:\Project\Dir1;C:\Project\Dir2

The Java interpreter will first look for MyClass class in the directory C:\Project\Dir1. Only if it doesn’t find it in that directory it will look in the C:\Project\Dir2 directory.

How to Add A Jar File To Java Load Path At Run Time

This can done by use of URLClassloader. A sample implementation of this code is shown below

 

import java.net.URL;

import java.net.URLClassLoader;

 

public class SimpleJarLoader {

 

public static void main(String args[]) {

if (args.length < 2) {

System.out.println(“Usage: [Class name] [Jar Path]”);

return;

}

try {

System.out.println(“Trying to load the class…”);

Class.forName(args[0]);

} catch (Exception ex) {

System.out.println(“Not able to load class…” + args[0]);

}

 

try {

String url = “jar:file:/” + args[1] + “!/”;

URL urls[] = { new URL(url) };

URLClassLoader cl = new URLClassLoader(urls,

SimpleJarLoader.class.getClassLoader());

System.out.println(“Looking into jar… ” + url);

cl.loadClass(args[0]);

System.out.println(“Woohoo….I found it”);

} catch (Exception ex) {

System.out.println(“Oops…Still cant find the jar”);

ex.printStackTrace();

}

}

}

You can run this code by below command. (Make sure to use forward slash “/” as directory separator.)

 

java SimpleJarLoader org.springframework.core.SpringVersion C:/spring.jar

 

The output is like this

 

Trying to load the class…

Not able to load class…org.springframework.core.SpringVersion

Looking into jar… jar:file:/C:/spring.jar!/

Woohoo….I found it

This functionality is provided by the Collections class, which is a wrapper implementation using the decorator design pattern.

public class ReadOnlyExample {

public static void main(String args[ ]) {

Set<string> set = new HashSet<string>( );

set.add(“Java”);

set.add(“JEE”);

set.add(“Spring”);

set.add(“Hibernate”);

set = Collections.unmodifiableSet(set);

set.add(“Ajax”);                                           // not allowed.

}

}

Spring has become very huge and bulky. So, don’t over do it by using all its features because of the hype that Spring is good. Look at what parts of Spring really provides some benefits for your project and use those parts. In most cases, it is much better to use proven frameworks like Spring than create your own equivalent solution from a maintenance and applying the best practices perspective. For example, all spring templates (jdbc, rest, jpa etc.) have the following advantages — perform common setup routines for you, let you skip the boilerplate and concentrate on the logic you want.

Spring MVC is probably not the best Web framework. There are other alternatives like Struts 2, Wicket, and JSF.  Having said this, Spring integrates well with the other Web frameworks like Struts, JSF, etc.

The XML files can get bloated. This can be minimized by carefully considering other options like annotations, JavaConfig, and having separate XML configuration files.

There are three types of dependency injection:

  • Constructor Injection(e.g. Spring): Dependencies are provided as constructor parameters.
  • Setter Injection(e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
  • Interface Injection(e.g. Avalon): Injection is done through an interface.

There are a number of high level conceptual architectures as discussed below. These individual architectures can be mixed and matched to produce hybrid architectures.

Model-View-Controller Architecture

Most web and stand-alone GUI applications follow this pattern. For example, Struts and Spring MVC frameworks and Swing GUI.

 

  • The model represents the core business logic and state.
  • The view renders the content of the model state by adding display logic.
  • The controller translates the interaction with the view into action to be performed by the model.

The actions performed by a model include executing the business logic  and changing the state of the model.Based on the user interactions, the controller selects an appropriate view to render.The controller decouples the model from the view.

Service Oriented Architecture (SOA)

The business logic and application state are exposed as reusable services.

An Enterprise Service Bus (ESB) is used as an orchestration and mediation layer to decouple the applications from the services.

 

The above architecture has 5 tiers. The application tier could be using a typical MVC architecture.

  • The service orchestration tier could be using ESB products like OracleService Bus, TIBCO, etc and BPM products like Lombardi BPM, Pega BPM, etc.
  • In the abovediagram, the ESB integrates with the BPM via messaging queues.
  • The service tier consists of individual services that can be accessed through SOAP or RESTful web services.
  • The SOA implementation requires change agents to drive adoption of new approaches.
  • The BPM,application integration, and real-time information all contribute to dynamically changing how business users do their jobs.

So, it needs full support from the business, requiring  restructuring and also it can take some time to realize the benefits of SOA. Cloud computing is at the leading edge of its hype and as a concept compliments SOA as an architectural style. Cloud computing is expected to provide a computing capability that can scale up (to massive proportions) or scale down dynamically based on demand. This implies a very large pool of computing resources either be within the enterprise intranet or on the Internet (i.e on the cloud).

User Interface (UI) Component Architecture

This architecture is driven by a user interface that is made up of a number of discrete components.Each component calls a service that encapsulates business logic and hides lower level details. Components can be combined to form new composite components allowing richer functionality. These components can also be shared across a number ofapplications.

For example, JavaScript widgets, Java Server Faces (JSF) components, etc.

 

RESTful data composition Architecture

The user interface can be built by calling a number of underlying services that are each responsible for building part of a page.

 

The user interface translates and combine the data in different formats like XML(translate to HTML using XSLT), JSON (Java Script Object Notation), ATOM (feed for mail messages and calendar applications), RSS (for generating RSS feeds), etc.

HTML composition Architecture

In this architecture, multiple applications output fragments of HTML that are combined to generate the final user interface.

 

For example, Java portlets used inside a portal application server to aggregate individual content..

Plug-in Architecture

In this architecture, a core application defines an interface, and the functionality will be implemented as a set of plug-ins that conform to that interface.

 

For example, the the Eclipse RCP framework, Maven build tool, etc use this architecture.

Event Driven Architecture (EDA)

The EDA pattern decouples the interactions between the event publishers and the event consumers. Many to many communications are achieved via a topic, where one specific event can be consumed by many subscribers. The EDA also supports asynchronous operations and acknowledgments through event messaging.

This architecture requires effective monitoring in place to track queue depth, exceptions, and other possible problems. The traceability, isolation, and debugging of an event can be difficult in some cases. This architecture is useful in scenarios where the business process is inherently asynchronous, multiple consumers are interested in an event(e.g. order status has changed to partially-filled ), no immediate acknowledgment is required (e.g. an email is sent with the booking details and itinerary), and real-time request/response is not required (e.g. a long running report can be generated asynchronously and made available later via online or via email).

 

 

 

Most conceptual architectures use a hybrid approach using a combination of different architectures based on the benefits of each approach and its pertinence to your situation. Here is a sample hybrid approach depicting an online trading system.

 

 

 

FIX is a Financial Information eXchange protocol. You could also notice a number of synchronous calls using XML/HTTP or SOAP/HTTP and asynchronous calls using JMS. The above diagram also depicts that an enterprise architecture can be complex with a number of moving parts. So, it is imperative that all these moving parts are properly monitored and tested for any potential performance issues. Most of these services will be running as a cluster or a load balanced service with either active/active or active.passive configuration for high availability and scalability.

Dependency Inversion Principle (DIP) is a design principle which is in some ways related to the Dependency Injection (DI) pattern. The idea of DIP is that higher layers of your application should not directly depend on lower layers. Dependency Inversion Principle does not imply Dependency Injection. This principle doesn’t say anything about how higher la yers know what lower layer to use. This could be done as shown below by coding to interface using a factory pattern or through Dependency Injection by using an IoC container like Spring framework, Pico container, Guice, or Apache HiveMind.

 

The Dependency Inversion Principle (DIP) states that High level modules should not depend upon low level modules. Both should depend upon abstractions.Abstractions should not depend upon details. Details should depend upon abstractions.When this principle is applied, the higher level classes will not be working directly with the lower level classes, but with anabstract layer. This gives us the flexibility at the cost of increased effort.Here are some code snippets for DIP.

Firstly define the abstraction layer.

package principle_dip2;

 

public interface AnimalHandler {

public abstract void handle( );

}

package principle_dip2;

 

public interface AnimalHelper {

public abstract void help( );

}

Now the implementation that depends on the abstraction as opposed to the implementation.

package principle_dip2;

 

public class CircusService {

AnimalHandler handler;

public void setHandler(AnimalHandler handler) {

this.handler = handler;

}

 

public void showStarts( ) {

//code omitted for brevity

handler.handle( );

}

}

package principle_dip2;

public class TigerHandler implements AnimalHandler{

AnimalHelper helper;

public void setHelper(AnimalHelper helper) {

this.helper = helper;

}

 

public void handle( ){

//…

helper.help( );

//…

}

}

package principle_dip2;

public class TigerHelper implements AnimalHelper{

 

public void help( ){

//……

}

}

Dependency Injection (DI) is a pattern of injecting a class’s dependencies into it at runtime. This is achieved by defining the dependencies as interfaces, and then injecting in a concrete class implementing that interface to the constructor. This allows you to swap in different implementations without having to modify the main class. The Dependency Injection pattern also promotes high cohesion by promoting the  Single Responsibility Principle (SRP), since your dependencies are individual objects which perform discrete specialized tasks like data access (via DAOs) and business services (via Service and Delegate classes).

The Inversion of Control Container (IoC) is a container that supports Dependency Injection. In this you use a central container  like Spring framework, Guice, or HiveMind, which defines what concrete classes should be used for what dependencies throughout your application. This brings in an added flexibility through looser coupling, and it makes it much easier to change what dependencies are used on the fly. The basic concept of the Inversion of Control pattern is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up. Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

The real power of DI and IoC is realized  in its ability to replace the compile time binding of the relationships between classes with  binding those relationships at runtime. For example, in Seam framework, you can have a real and mock implementation of an interface, and at runtime decide which one to use based on a property, presence of another file, or some precedence values. This is incredibly useful if you think you may need to modify the way your application behaves in different scenarios. Another real benefit of DI and IoC is that it makes your code easier to unit test. There are other benefits like promoting looser coupling without any proliferation of factory and singleton design patterns, follows a consistent approach for lesser experienced developers to follow, etc. These benefits can come in at the cost of the added complexity to your application and has to be carefully manged by using them only at the right places where the real benefits are realized, and not just using them because many others are using them.

Note: The CDI (Contexts and Dependency Injection)  is an attempt at describing a true standard on Dependency Injection. CDI is a part of the Java EE 6 stack, meaning an application running in a Java EE 6 compatible container can leverage CDI out-of-the-box. Weld is the reference implementation of CDI.

Spring has a layered architecture with over 20 modules to choose from. This means, use what you need and leave what you don’t need now. Spring simplifies JEE through POJO programming. There is no behind the scene magic in Spring as in JEE programming. POJO programming enables continuous integration and testability.

 

Spring framework’s core functionality is dependency injection (DI). Dependency injection promotes easy unit testing and more maintainable and flexible code. DI code is much easier to test. The functionality expressed by the object can be tested in a black box by building ‘mock’ objects implementing the interfaces expected by yourapplication logic. DI code is much easier to reuse as the ‘depended’ functionality is extrapolated into well defined interfaces, allowing separate objects whose configuration is handled by a suitable application platform to be plugged into other objects at will. DI code is more flexible. It is innately loosely coupled code to an extreme. This allows the programmer to pick and choose how objects are connected based exclusively on their required interfaces on one end and their expressed interfaces on the other.

Spring supports Aspect Oriented Programming (AOP), which enables cohesive development by separatingapplication business logic from system services. Supporting functionalities like auditing, gathering performance and memory metrics, etc can be enabled through AOP.

Spring also provides a lot of templates which act as base classes to make using the JEE standard technologies a breeze to work with. For example, the JdbcTemplate works well with JDBC, the JpaTemplate does good things with JPA, JmsTemplate makes JMS pretty straightforward. The RestTemplate is simply awesome in it’s simplicity. Simplicity means more readable and maintainable code.When writing software these days, it is important to try and decouple as much middleware code from your business logic as possible. The best approach when using remoting is to use Spring Remoting which can then use any messaging or remoting technology under the covers. Apache Camel is a powerful open source integration framework based on known Enterprise Integration Patterns with powerful Bean Integration. Apache Camel is designed to work nicely with the Spring Framework in a number of ways.

It also provides declarative transactions, job scheduling, authentication, a fully-fledged MVC webframework, and integration to other frameworks likeHibernate,iBatis,JasperReports,JSF,Struts,Tapestry,Seam, Quartz job scheduler, etc.

Spring beans can be shared between different JVMs using Terracotta. This allows you to take existing beans and spread them across a cluster, turn Spring application context events into distributed events, export clustered beans via Spring JMX, and make your Spring applications highly available and clustered. Spring also integrate well with other clustering solutions like Oracle’s Coherance.Spring favors unchecked exceptions and eliminates unsightly try, catch, and finally (and some times try/catch within finally itself) blocks. The Spring templates like JpaTemplate takes care of closing or releasing a database connection. This prevents any potential resource leaks and promotes more readable code.It prevents the proliferation of factory and singleton pattern classes that need to be created to promote loose coupling if not for using a DI framework like Spring or Guice.