Wednesday, 29 May 2013

Spring Basic Interview Questions Part-1 !

Interview Questions

Question: - What is a container?

Answer: - Container is nothing but a piece of code; It is used to define any component that can contain other components inside itself. We can say that container provides groundwork to a component that is needed by it to survive.


We can think in a way that a servlet container like Tomcat where a servlet executes and alive. Similarly we can imagine about any application server which is providing an infrastructure like EJB container where enterprise java-beans survives. In the similar manner, we can say that spring provides a container where spring beans resides and works. The primary job of spring container is to manage the lifecycle and relationships between many objects. It does that by loading them in its container. Spring is a container in the sense that it contains and manages the lifecycle and configuration of application objects. In spring, we can declare how our application objects should be created, how they should be configured, and how they should be associated with each other.



The org.springframework.beans.factory.BeanFactory is the actual representation of the Spring IOC container that is responsible for containing and otherwise managing the former beans.



Spring BeanFactory Container: - A basic container which is providing support for Dependency Injection. A BeanFactory is an implementation of the factory pattern. The BeanFactory interface is the central IoC container interface in Spring. Its responsibilities include instantiating or sourcing application objects, configuring such objects, and assembling the dependencies between these objects. This basic interface is used to access all bean factories. The getBean(String name) method of this interface allows us to get a bean from the container by name and also the getBean(String name, Class requiredClassName) method from the same interface allows us to specify the required class of the returned bean and it will throw an exception if the required class doesn't exist.



Using following way, we can start the spring BeanFactory container:-



Resource resource = new FileSystemResource("beans.xml");

                        XmlBeanFactory xmlFactory = new XmlBeanFactory(resource);

                        UserInfo uinfo  = (UserInfo)xmlFactory.getBean("userInfoId");

Or

ClassPathResource classPathResource = new ClassPathResource("beans.xml");
                        XmlBeanFactory xmlFactory = new XmlBeanFactory(classPathResource);
                        UserInfo uinfo  = (UserInfo)xmlFactory.getBean("userInfoId");

Or

BeanFactory beanFactory = new ClassPathXmlApplicationContext(
                                new String[] {"beans.xml"});
                        UserInfo uinfo  = (UserInfo)beanFactory.getBean("userInfoId");

Spring ApplicationContext Container: - The ApplicationContext created on top of the BeanFactory (a subclass) and adds other functionality such as easier integration with Springs AOP features, message resource handling (use in internationalization), event propagation, declarative mechanisms to create the ApplicationContext, and application-layer specific contexts such as  WebApplicationContext. ApplicationContext is an interface for providing configuration information to an application. This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by the org.springframework.context.ApplicationContext interface.

Using following way, we can start the spring ApplicationContext container:-

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
                        UserInfo uinfo = (UserInfo)ctx.getBean("userInfoId");

Or

ApplicationContext appContext = new FileSystemXmlApplicationContext("beans.xml");
                        UserInfo userInfo = (UserInfo)appContext.getBean("userInfoId");
 


Question: - What is the difference between BeanFactory and ApplicationContext?




Answer: - Difference between BeanFactory and ApplicationContext


BeanFactory V/S ApplicationContext


  • As the ApplicationContext container is created on top of BeanFactory and includes all functionality of the BeanFactory container, so always it is better approach to use ApplicationContext instead of BeanFactory.
  • In case of light weight application development like application for mobile devices, BeanFactory can still be used.
  • In Case when we are working with applet based applications where application performance needs to maintain and we have to keep on eye on data volume, there also we can use BeanFactory.
  • When we want to use complete configuration responsibilities, capabilities and assembling the dependencies, then in that case we can go with ApplicationContext. 

Question: - What is a bean?

Answer: - In Spring, the objects that are responsible to form the backbone of our application and that are managed by the Spring IoC container is referred to as beans. A bean is simply an object that is instantiated, assembled and otherwise managed by a Spring IoC container.

Question: - What is Inversion of Control (IoC)?

Answer: - As per oop's programming, Inversion of Control (IoC) is a programming technique/ concept in which object coupling is bound at run time by an assembler object. It is a pattern used for decoupling components and layers in the system. IoC allows us to decouple our program into separate components that don't know about each other or we can say that it is providing a way to wire components through dependency injection design pattern. IoC is all about providing power of more flexibility and less dependency.

Advantages of IoC:-
  • We can reduce the programming complexity using IoC.
  • We can easily tests programming components independently using mock objects.
  • Components can be easily switched to another implementation with less or no effort.
  • Providing a way to share resources throughout the application.

Below are the few techniques to implement inversion of control (IoC):-
1)      Using dependency injection
Dependency injection can be achieved in three ways:-
         a) Constructor injection
         b) Setter injection
         c) Interface injection: - It is not supported by spring. Apache Avalon framework was supporting this 
             but now this project is closed.
2)      Using factory design pattern.
      3)   Using service locator design pattern


Question: - What is dependency injection?


Answer: -  Dependency injection is a design pattern that allows removing hard-coded dependencies and making it possible to change them dynamically. So the binding process during the inversion of control is achieved through dependency injection and this is one way to achieve IoC.  




Dependency injection follows a principle i.e. don’t call us, we'll call you.



Advantages:-




  • DI is providing loosely coupled architecture between classes and subsystems.

  • DI is easy to implement.

  • JUnit test can be performed easily and also we can take help of Mockito mock objects.

  • It helps in removing boiler plate code from the application

  • It provides flexible configuration because alternative implementations of a given service can be used without recompiling the code.

Demo Example of Tightly coupled components:-

package com.gaurav.tightcoupling.example;

public class Address {

    private String streetNumber;
    private String colonyName;
    private String cityName;
    private String state;
    private String pin;

    /**
     * @return the streetNumber
     */
    public String getStreetNumber() {
        return streetNumber;
    }

    /**
     * @param streetNumber
     *            the streetNumber to set
     */
    public void setStreetNumber(String streetNumber) {
        this.streetNumber = streetNumber;
    }

    /**
     * @return the colonyName
     */
    public String getColonyName() {
        return colonyName;
    }

    /**
     * @param colonyName
     *            the colonyName to set
     */
    public void setColonyName(String colonyName) {
        this.colonyName = colonyName;
    }

    /**
     * @return the cityName
     */
    public String getCityName() {
        return cityName;
    }

    /**
     * @param cityName
     *            the cityName to set
     */
    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    /**
     * @return the state
     */
    public String getState() {
        return state;
    }

    /**
     * @param state
     *            the state to set
     */
    public void setState(String state) {
        this.state = state;
    }

    /**
     * @return the pin
     */
    public String getPin() {
        return pin;
    }

    /**
     * @param pin
     *            the pin to set
     */
    public void setPin(String pin) {
        this.pin = pin;
    }

}

Student.java
 
package com.gaurav.tightcoupling.example;
public class Student {
    private int studentId;
    private String studentName;
    private Address address;
    /**
     * @return the studentId
     */
    public int getStudentId() {
        return studentId;
    }
    /**
     * @param studentId
     *            the studentId to set
     */
    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }
    /**
     * @return the studentName
     */
    public String getStudentName() {
        return studentName;
    }
    /**
     * @param studentName
     *            the studentName to set
     */
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    /**
     * @return the address
     */
    public Address getAddress() {
        return address;
    }
    /**
     * @param address
     *            the address to set
     */
    public void setAddress(Address address) {
        this.address = address;
    }
}
/**
 * Note:- Here Address object is dependent on Student object. As we are using
 * Address object in the student class.
 *
 * */
 


TestTightCoupling.java

package com.gaurav.tightcoupling.example;
public class TestTightCoupling {
    public static void main(String args[]) {
        Student student = new Student();
        student.setStudentId(324534);
        student.setStudentName("KUMAR GAURAV");
        Address address = new Address();
        address.setCityName("Hyderabad");
        address.setColonyName("Hi-Tech City");
        address.setStreetNumber("23/66");
        address.setState("Andhra pradesh");
        address.setPin("235612");
        student.setAddress(address);
        System.out.println("student id is:-" + student.getStudentId());
        System.out.println("student name is:-" + student.getStudentName());
        System.out.println("student street number is:-"
                + student.getAddress().getStreetNumber());
        System.out.println("student colony came is:-"
                + student.getAddress().getColonyName());
        System.out.println("student city name is:-"
                + student.getAddress().getCityName());
        System.out.println("student state is:-"
                + student.getAddress().getState());
        System.out.println("student pin is:-" + student.getAddress().getPin());
    }
}

Result:- 


student id is:-324534
student name is:-KUMAR GAURAV
student street number is:-23/66
student colony came is:-Hi-Tech City
student city name is:-Hyderabad
student state is:-Andhra pradesh
student pin is:-235612

Demo Example of Loosely coupled components:-

HelperInterface.java

package com.gaurav.loosecoupling.example;
public interface HelperInterface {
    public void setAddress(Address address);
    public Address getAddress();
} 

Address.java

package com.gaurav.loosecoupling.example;
public class Address implements HelperInterface{
    private String streetNumber;
    private String colonyName;
    private String cityName;
    private String state;
    private String pin;
   /**
     * @return the streetNumber
     */
    public String getStreetNumber() {
        return streetNumber;
    }
    /**
     * @param streetNumber the streetNumber to set
     */
    public void setStreetNumber(String streetNumber) {
        this.streetNumber = streetNumber;
    }
    /**
     * @return the colonyName
     */
    public String getColonyName() {
        return colonyName;
    }
    /**
     * @param colonyName the colonyName to set
     */
    public void setColonyName(String colonyName) {
        this.colonyName = colonyName;
    }
    /**
     * @return the cityName
     */
    public String getCityName() {
        return cityName;
    }
    /**
     * @param cityName the cityName to set
     */
    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
    /**
     * @return the state
     */
    public String getState() {
        return state;
    }
    /**
     * @param state the state to set
     */
    public void setState(String state) {
        this.state = state;
    }
    /**
     * @return the pin
     */
    public String getPin() {
        return pin;
    }
    /**
     * @param pin the pin to set
     */
    public void setPin(String pin) {
        this.pin = pin;
    }
   

    @Override
    public void setAddress(Address address) {
        this.streetNumber = address.getStreetNumber();
        this.colonyName = address.getColonyName();
        this.cityName = address.getCityName();
        this.state = address.getState();
        this.pin = address.getPin();
    }
    @Override
    public Address getAddress() {
        return new Address();
    }
}

Student.java

package com.gaurav.loosecoupling.example;

public class Student {
    private int studentId;
    private String studentName;
    HelperInterface helperInterface;
   
    public Student(HelperInterface hlpInterface){
        this.helperInterface = hlpInterface;
    }

    /**
     * @return the studentId
     */
    public int getStudentId() {
        return studentId;
    }

    /**
     * @param studentId the studentId to set
     */
    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    /**
     * @return the studentName
     */
    public String getStudentName() {
        return studentName;
    }

    /**
     * @param studentName the studentName to set
     */
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
}
/**
 * Note:- Here Address object and Student object is independent. As we are not exposing Address 
 * object directly in the student class. For this we are taking help of interface and we are able to
 * reduce the coupling between Student and Address objects.
 * */


TestLooseCoupling.java

package com.gaurav.loosecoupling.example;

public class TestLooseCoupling {

public static void main(String args[]){
   
        HelperInterface helperInterface = new Address();

        Student student = new Student(helperInterface);
        student.setStudentId(324534);
        student.setStudentName("KUMAR GAURAV");
      
        System.out.println("student id is:-"+student.getStudentId());
        System.out.println("student name is:-"+student.getStudentName());
      
        Address address = helperInterface.getAddress();
        address.setCityName("Hyderabad");
        address.setColonyName("Hi-Tech City");
        address.setStreetNumber("75/11");
        address.setState("Andhra pradesh");
        address.setPin("235612");
      
        System.out.println("student street number is:-"+address.getStreetNumber());
        System.out.println("student colony came is:-"+address.getColonyName());
        System.out.println("student city name is:-"+address.getCityName());
        System.out.println("student state is:-"+address.getState());
        System.out.println("student pin is:-"+address.getPin());
    }
}

Result:-

student id is:-324534
student name is:-KUMAR GAURAV
student street number is:-75/11
student colony came is:-Hi-Tech City
student city name is:-Hyderabad
student state is:-Andhra pradesh
student pin is:-235612

About Spring Questions                Spring Basic Questions Part-3

No comments:

Post a Comment