Spring Interview Questions Answers - Mostly Asked 1

Spring Interview Questions 1



Q. Explain DI or IOC pattern. 

A:  Dependency injection (DI) is a programming design pattern and architectural model, sometimes also referred to as inversion of control or IOC, although technically speaking, dependency injection specifically refers to an implementation of a particular form of IOC. Dependancy Injection describes the situation where one object uses a second object to provide a particular capacity. For example, being passed a database connection as an argument to the constructor instead of creating one internally. The term "Dependency injection" is a misnomer, since it is not a dependency that is injected, rather it is a provider of some capability or resource that is injected. There are three common forms of dependency injection: setter-, constructor- and interface-based injection. Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way in which an object obtains references to its dependencies. This is often done by a lookup method. The advantage of inversion of control is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing.

Q. What are the different IOC containers available?

A. Spring is an IOC container. Other IOC containers are HiveMind, Avalon, PicoContainer.

Q. What are the different types of dependency injection. Explain with examples.

A: There are two types of dependency injection: setter injection and constructor injection.
Setter Injection:  Normally in all the java beans, we will use setter and getter method to set and get the value of property as follows:
 

    public class NameBean {
     String      name;
     public void setName(String a) {   name = a; }
     public String getName() {   return name; }
    }
 
We will create an instance of the bean 'NameBean' (say bean1) and set property as bean1.setName("tom"); Here in setter injection, we will set the property 'name'  in spring configuration file as showm below: <bean id="bean1"   class="NameBean">
   <property   name="name" >
       <value>tom</value>
   </property>
</bean>

The subelement <value> sets the 'name' property by calling the set method as setName("tom"); This process is called setter injection.
To set properties that reference other beans <ref>, subelement of <property> is used as shown below,
 
<bean id="bean1"   class="bean1impl">
   <property name="game">
       <ref bean="bean2"/>
   </property>
</bean>
<bean id="bean2"   class="bean2impl" />
 
Constructor injection:  For constructor injection, we use constructor with parameters as shown below,
 

 public class namebean {
     String name;
     public namebean(String a) {
        name = a;
     }
}
 
We will set the property 'name' while creating an instance of the bean 'namebean' as namebean bean1 = new namebean("tom");
 
Here we use the <constructor-arg> element to set the the property by constructor injection as
 <bean id="bean1"  class="namebean">
    <constructor-arg>
       <value>My Bean Value</value>
   </constructor-arg>
</bean>
 

Q. What is spring? What are the various parts of spring framework? What are the different persistence frameworks which could be used with spring?

A. Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development. The Spring modules are built on top of the core container, which defines how beans are created, configured, and managed, as shown in the following figure. Each of the modules (or components) that comprise the Spring framework can stand on its own or be implemented jointly with one or more of the others. The functionality of each component is as follows:

The core container: The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application’s configuration and dependency specification from the actual application code.

Spring context: The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality.

Spring AOP: The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.

Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO’s JDBC-oriented exceptions comply to its generic DAO exception hierarchy.

Spring ORM: The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring’s generic transaction and DAO exception hierarchies.

Spring Web module: The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.

Spring MVC framework: The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI.



Q. What is AOP? How does it relate with IOC? What are different tools to utilize AOP?

A:  Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. AOP and IOC are complementary technologies in that both apply a modular approach to complex problems in enterprise application development. In a typical object-oriented development approach you might implement logging functionality by putting logger statements in all your methods and Java classes. In an AOP approach you would instead modularize the logging services and apply them declaratively to the components that required logging. The advantage, of course, is that the Java class doesn't need to know about the existence of the logging service or concern itself with any related code. As a result, application code written using Spring AOP is loosely coupled. The best tool to utilize AOP to its capability is AspectJ. However AspectJ works at he byte code level and you need to use AspectJ compiler to get the aop features built into your compiled code. Nevertheless AOP functionality is fully integrated into the Spring context for transaction management, logging, and various other features.  In general any AOP framework control aspects in three possible ways:
 

Joinpoints: Points in a program's execution. For example, joinpoints could define calls to specific methods in a class
Pointcuts: Program constructs to designate joinpoints and collect specific context at those points
Advices: Code that runs upon meeting certain conditions. For example, an advice could log a message before executing a joinpoint
 

Q. What are the advantages of spring framework?

  1. Spring has layed architecture. Use what you need and leave you don't need now.
  2. Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continous integration and testability.
  3. Dependency Injection and Inversion of Control Simplifies JDBC (Read the first question.)
  4. Open source and no vendor lock-in.

Q. Explain BeanFactory in spring.

A: Bean factory is an implementation of the factory design pattern and its function is to create and dispense beans. As the bean factory knows about many objects within an application, it is able to create association between collaborating objects as they are instantiated. This removes the burden of configuration from the bean and the client. There are several implementation of BeanFactory. The most useful one is "org.springframework.beans.factory.xml.XmlBeanFactory" It loads its beans based on the definition contained in an XML file. To create an XmlBeanFactory, pass a InputStream to the constructor. The resource will provide the XML to the factory. BeanFactory  factory = new XmlBeanFactory(new FileInputStream("myBean.xml"));
This line tells the bean factory to read the bean definition from the XML file. The bean definition includes the description of beans and their properties. But the bean factory doesn't instantiate the bean yet. To retrieve a bean from a 'BeanFactory', the getBean() method is called. When getBean() method is called, factory will instantiate the bean and begin setting the bean's properties using dependency injection. 
myBean bean1 = (myBean)factory.getBean("myBean");

Q. Explain the role of ApplicationContext in spring.

A. While Bean Factory is used for simple applications, the Application Context is spring's more advanced container. Like 'BeanFactory' it can be used to load bean definitions, wire beans together and dispense beans upon request. It also provide
1) a means for resolving text messages, including support for internationalization.
2) a generic way to load file resources.
3) events to beans that are registered as listeners.
 
Because of additional functionality, 'Application Context' is preferred over a BeanFactory. Only when the resource is scarce like mobile devices, 'BeanFactory' is used. The three commonly used implementation of 'Application Context' are
 

1. ClassPathXmlApplicationContext : It Loads  context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code 
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
2. FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code
ApplicationContext    context = new FileSystemXmlApplicationContext("bean.xml");
3. XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.
 

Q. How does Spring supports DAO in hibernate?

A. 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.
Example:
 

public class UserDAOHibernate extends HibernateDaoSupport {
 
public User getUser(Long id) {
return (User) getHibernateTemplate().get(User.class, id);
}
public void saveUser(User user) {
getHibernateTemplate().saveOrUpdate(user);
if (log.isDebugEnabled()) {
log.debug(“userId set to: “ + user.getID());
}
}
public void removeUser(Long id) {
Object user = getHibernateTemplate().load(User.class, id);
getHibernateTemplate().delete(user);
}
 
}

Q. How is a typical spring implementation look like?

A. For a typical Spring Application we need the following files  
1. An interface that defines the functions.
2. An Implementation that contains properties, its setter and getter methods, functions etc.,
3. A XML file called Spring configuration file.
4. Client program that uses the function.  

Q. Can you have xyz.xml file instead of applicationcontext.xml?  

A. ContextLoaderListener is a ServletContextListener that initializes when your webapp starts up. By default, it looks for Spring’s configuration file at WEB-INF/applicationContext.xml. You can change this default value by specifying a <context-param> element named “contextConfigLocation.” Example:
 

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener> 
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/xyz.xml</param-value>
    </context-param> 
    </listener-class>
</listener>

Q. How do you configure spring in a web application?  

A. It is very easy to configure any J2EE-based web application to use Spring. At the very least, you can simply add Spring’s ContextLoaderListener to your web.xml file:
 
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

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

A. Using "org.springframework.jndi.JndiObjectFactoryBean". Example:

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName">
        <value>java:comp/env/jdbc/appfuse</value>
    </property>
</bean>

Q. How do you configure your database driver in spring?

A. Using datasource "org.springframework.jdbc.datasource.DriverManagerDataSource".
Example:
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName">
        <value>org.hsqldb.jdbcDriver</value>
    </property>
    <property name="url">
        <value>jdbc:hsqldb:db/appfuse</value>
    </property>
    <property name="username"><value>sa</value></property>
    <property name="password"><value></value></property>
</bean>

Excel to Wiki table converter

Tab separated table - Excel / Google Sheet to Wiki table converter



Input : Paste Tab-separated table data ( eg : row/column from Excel, Google Docs etc)

Output : MediaWiki formatted table





Source : GitHub

Logging levels - meanings and use

All the popular logging frameworks follow the similar convention and naming for log levels. There are five priority levels in use.

Order ( high priority to low):
  • FATAL ERROR WARN INFO DEBUG TRACE
Meaning and Use:
  1. debug to write debugging messages which should not be printed when the application is in production.
  2. info for messages similar to the "verbose" mode of many applications.
  3. warn for warning messages which are logged to some log but the application is able to carry on without a problem.
  4. error for application error messages which are also logged to some log but, still, the application can hobble along. Such as when some administrator-supplied configuration parameter is incorrect and you fall back to using some hard-coded default value.
  5. fatal for critical messages, after logging of which the application quits abnormally.
 Additionally, there are two other levels. They have the obvious meanings.
  1. ALL
  2. OFF

grails detecting environment - groovy & gsp code

Grails/Groovy working code snippet to detect the current environment (development, test, production, or your  custom). Custom environment are defined in config.groovy file.

Detecting Environment in GSP code :

Following checks if current environment is other than production.
    <g:if test="${env != "production"}">
        //your logic 

    </g:if>

Detecting environment in Groovy Code ( in Controller, Service, etc..), using switch-case comparison

        switch(Environment.current.getName()){
            case "development":
                //do your stuff 1
                break;
            case "test":
                //do your stuff 2
                break;
            case "production":
                //do your stuff 3
                break;
            case "my_environment":  // for custom environment : my_environment
                //todo:
                break;
        }

Simple comparison in groovy

if(Environment.current.getName()=="development") {
    //do your stuff
}

Grails - auto login in spring security

Consider a typical web application where you have multiple user roles (like SUPER_ADMIN, OPERATOR, VISITOR etc ) and you need to do login and switch between them frequently. It certainly consumes a lot of time if you do this manually. One simple solution would be to use the browser's password remember feature. But this would not be useful if you need to switch between different role.

Here, I am going to do show how we can setup this mechanism in Grails applications which uses Spring Security plugin.

If you are using Spring Security plugin then, by default you will have following names for html textbox for username and password : j_username and j_password. and you have login request url as http://localhost:8080/YOUR_APP/j_spring_security_check .

The required login script :

Groovy Grails - Dynamic Method n Variable name and invoking them

Groovy allows to use dynamic method name and variable name and invoke/use them.

Dynamic Variable Names

Groovy allows to use variable name dynamically. To test this lets introduce a variable  "dogname" to Dog class

class Dog {
def dogname
...
}

//Testing dynamic variable name
        def aDog= new Dog()
aDog.name="Hachi"
def prop="dogname"

println aDog."$prop" // prints Hachi

git- saving username password - credential.helper cache - how to

Isn't is interesting if there is an option in GIT to save your credentials for short time so that you don't enter your username/password repeatedly each time when you do pull/push? Yes! there is an option introduced in GIT since 1.7.9 (released on January 2012). This method is more secure than permanently saving your username/password in   .git  file of your git clone directory.

So, run the following command at the GIT console (git bash) :
git config --global credential.helper cache
This caches the credentials for 15 minutes ( 900 seconds) by default. If you want a longer timeout period (say3600 seconds), you can do the following :
git config --global credential.helper 'cache --timeout=3600'

Grails - beginners video tutorial


From the Grails site: "Grails aims to bring the 'coding by convention' paradigm to Groovy. It's an open-source web application framework that leverages the Groovy language and complements Java Web development. You can use Grails as a standalone development environment that hides all configuration details or integrate your Java business logic. Grails aims to make development as simple as possible and hence should appeal to a wide range of developers not just those from the Java community."

grails- add jar to lib folder - not working - solution

In grails application you can add jar dependencies by just pasting the .jar file to lib folder. If your code doesn't find the jar dependency at runtime then you can do following :

Run the following grail command (s):
  • clean
  • compile --refresh-dependencies 
In eclipse you can open the Grails Command Prompt by :
Right Click on project -> Grail Tools -> Open Grails Command Prompt

Hope this helps.

nepali english date conversion logic - working java code


My friend Manoj has written about Nepali-English date conversion in this post. Take a look :

http://forjavaprogrammers.blogspot.com/2012/06/how-to-convert-english-date-to-nepali.html

He has explained the algorithm in detail about how to convert English dates into Nepali dates with java code.