Spring core interview questions
By: Disha Saxena
Tags: Learning, Interview Questions, Spring Framework, Spring, Java8

SPRING CORE

Spring framework is an open-source Java platform that provides comprehensive infrastructure support for developing robust Java applications very easily and very rapidly

Spring IOC container:

The Spring container is at the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete life cycle from creation till destruction. The Spring container uses DI to manage the components that make up an application.

Ques 1: How many types of injection?

Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control).

Spring documentation strictly defines only two types of injection:

1. Constructor Injection: In this, the DI will be injected with the help of constructors. Now to set the DI as CDI in the bean, it is done through the bean-configuration file. For this, the property to be set with the CDI is declared under the <constructor-arg> tag in the bean-config file.

2. Setter Injection: In this, the DI will be injected with the help of setter and/or getter methods. Now to set the DI as SDI in the bean, it is done through the bean-configuration file For this, the property to be set with the SDI is declared under the <property> tag in the bean-config file.

Ques 2: At what time the object is created (reading or calling) in the main class? Is it eager or lazy loading, if it is lazy change it to eager and vice versa?

By default, Spring “application context” Eagerly creates and initializes all ‘singleton scoped‘ beans during application startup itself. It helps in detecting the bean configuration issues at an early stage, in most of the cases. But sometimes, you may need to mark some or all beans to be lazily initialized due to different project requirements.

Spring provides two easy ways to configure lazy initialization of beans based on which kind of configuration you are employing i.e. XML based configuration or java based configuration.

1. @Lazy initialized beans — Java configuration

@Lazy load specific bean

To lazy load, only specific beans, use @Lazy annotation along with @Bean annotation in java config.

AppConfig.java

import org.springframework.context.annotation.Lazy;

@Configuration

public class AppConfig {

@Lazy

@Bean

public EmployeeManager employeeManager() {

return new EmployeeManagerImpl();

}

}

Lazy load all beans

To lazy load, all beans, use @Lazy annotation along with @Bean annotation in java config.

AppConfig.java

import org.springframework.context.annotation.Lazy;

@Lazy

@Configuration

public class AppConfig {

@Bean

public EmployeeManager employeeManager() {

return new EmployeeManagerImpl();

}

}

@Autowired lazy beans

Generally, beans are injected into other components using @Autowired annotation. In this case, we must use the lazy annotation at both places:

· The bean definition which you want to lazy load

· The place it is injected along with @Autowired annotation

@Lazy

@Service

public class EmployeeManagerImpl implements EmployeeManager {

//

}

@Controller

public class EmployeeController {

@Lazy

@Autowired

EmployeeManager employeeManager;

}

NOTE: Without using @Lazy annotation at both places, it will not work.

2. Lazy initialized beans in XML configuration

→Lazy load specific beans only

To enable lazy loading for specific beans, use lazy-init=”true” attribute on bean definitions in bean configuration xml files.

→Lazy load all beans globally

To enable lazy loading for all beans, use default-lazy-init=”true” attribute on beans tag in bean configuration xml files.

beans.xml

<beans default-lazy-init=”true”>

<bean id=”employeeManager” class=”com.learning.spring.service.impl.EmployeeManagerImpl” />

<beans>

Ques 3: When we call get beans two times what happens how many object are created?

The Spring Framework supports the following five scopes, three of which are available only if you use a web-aware ApplicationContext.

singleton: only one instance of the spring bean will be created for the spring container. This is the default spring bean scope. While using this scope, make sure bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues.

prototype: A new instance will be created every time the bean is requested from the spring container.

Eg: <bean id = “Collectiontype” class = “com.spring.Collection.CollectionType” scope=”singleton”>

request: This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.

session: This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

global-session: This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

Ques 4: Can we have duplicate id in xml bean?

No, we can’t have duplicate id’s. The given Spring context can only have one bean for any given id or name. In the case of the XML id attribute, this is enforced by the schema validation. In the case of the name attribute, this is enforced by Spring’s logic.

However, if a context is constructed from two different XML descriptor files, and an id is used by both files, then one will “override” the other. The exact behavior depends on the ordering of the files when they get loaded by the context.

So while it’s possible, it’s not recommended. It’s error-prone and fragile, and you’ll get no help from Spring if you change the ID of one but not the other.

Ques 5: What happens if we have constructer args and setter argument both in xml ?

There will be no error, but then it will execute the setter argument.

Ques 6: Can I instantiate the same property more than once?

It is valid as long as you are defining two bean definitions with the same id of the same bean on two different spring configuration files. And you are importing one configuration file into another (kind of merging), does not matter how you are importing. The later one or the last one bean definition will be overridden by the first one.

But if you are defining the two bean definitions with the same bean id of the same bean in the same file you will find spring application start-up failed. Spring would not let you define multiple bean definitions of the same bean with the same name in the same spring configuration file.

Ques 7: Can I give an alias name for my bean?

Yes, we can even create two alias (different names) for the same bean. An aliased bean will always have higher priority over a non-aliased one, and in case of having different beans with the same alias then the last one declared will have the priority. In other words, the aliased bean will override the non-aliased beans.

Ques 8: Can I create a relation between xml file?

Yes, by importing a property from one .xml into another .xml.

<import resource=”Spring-Datasource.xml” />

<import resource=”Spring-Customer.xml” />

Ques 9: Inheritance relation between classes?

<bean id=”employeeBean” class=”org.spring.learning.Employee” parent=”id

or name of parent bean”>

1. Class Person with id as “PersonBean”

2. Class Employee with id as “EmployeeBean”

We have used parent property to show that Person is the parent class of Employee

package org.spring.learning;

public class Person {

String name;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

package org.spring.learning;

public class Employee extends Person{

int employeeNumber;

public int getEmployeeNumber() {

return employeeNumber;

}

public void setEmployeeNumber(int employeeNumber) {

this.employeeNumber = employeeNumber;

}

}

.xml file

<?xml version=”1.0" encoding=”UTF-8"?>

<beans xmlns=”http://www.springframework.org/schema/beans"

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance" xmlns:aop=”http://www.springframework.org/schema/aop"

xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id=”personBean” class=” org.spring.learning.Person”>

<property name=”name” value=”disha”/>

</bean>

<bean id=”employeeBean” class=” org.spring.learning.Employee” parent=”personBean”>

<property name=”employeeNumber” value=”178230" />

</bean>

</beans>

public class InheritenceInSpringMain {

public static void main(String[] args) {

ApplicationContext appContext = new ClassPathXmlApplicationContext(“ApplicationContext.xml”);

Employee emp=(Employee) appContext.getBean(“employeeBean”);

System.out.println(“Employee name:”+emp.getName());

System.out.println(“Employee number:”+emp.getEmployeeNumber());

}

}

Ques 10: How can we make use of the factory method to make an object?

In Spring framework, if you want to create a bean by invoking a static factory-method, whose purpose is to encapsulate the object-creation process in a static method then you could use factory-method attribute.

public class EmployeeDTO {

private Integer id;

private String firstName;

private String lastName;

private String designation;

//Setters and Getters

@Override

public String toString() {

return “Employee [id=” + id + “, firstName=” + firstName

+ “, lastName=” + lastName + “, type=” + designation + “]”;

}

}

public class EmployeeFactory {

public static EmployeeDTO createEmployeeOfType(String type)

{

if (“manager”.equals(type) || “director”.equals(type))

{

EmployeeDTO employee = new EmployeeDTO();

employee.setId(-1);

employee.setFirstName(“dummy”);

employee.setLastName(“dummy”);

//Set designation here

employee.setDesignation(type);

return employee;

}

else

{

throw new IllegalArgumentException(“Unknown product”);

}

}

}

<bean id=”manager” class=”com.spring.learning.factory.EmployeeFactory”

factory-method=”createEmployeeOfType”>

<constructor-arg value=”manager” />

</bean>

<bean id=”director” class=”com.sping.learning.factory.EmployeeFactory”

factory-method=”createEmployeeOfType”>

<constructor-arg value=”director” />

</bean>

public class TestSpringStaticFactoryMethod

{

@SuppressWarnings(“resource”)

public static void main(String[] args) throws Exception

{

ApplicationContext context = new ClassPathXmlApplicationContext(“applicationContext.xml”);

EmployeeDTO manager = (EmployeeDTO) context.getBean(“manager”);

System.out.println(manager);

EmployeeDTO director = (EmployeeDTO) context.getBean(“director”);

System.out.println(director);

}

}

Ques 11: How can we work with the interface?

When you define an interface for your classes, it helps with dependency injection. Your Spring configuration files don’t have anything about interfaces in them themselves àyou just put in the name of the class.

But if you want to inject another class that offers “equivalent” functionality, using an interface really helps.

public interface Shape

{

void draw();

}

public class Triangle implements Shape

{

private Point pointA;

private Point pointB;

private Point pointC;

public void setPointA(Point pointA) {

this.pointA = pointA;

}

public void setPointB(Point pointB) {

this.pointB = pointB;

}

public void setPointC(Point pointC) {

this.pointC = pointC;

}

public void draw()

{

System.out.println(“Drawing Triangle”);

System.out.println(“PointA is (“+pointA.getX()+”, “+pointA.getY()+”)”);

System.out.println(“PointB is (“+pointB.getX()+”, “+pointB.getY()+”)”);

System.out.println(“PointC is (“+pointC.getX()+”, “+pointC.getY()+”)”);

}

}

Circle.java

public class Circle implements Shape

{

private Point center;

public void setCenter(Point center)

{

this.center = center;

}

@Override

public void draw()

{

System.out.println(“Circle is drawn of center (“+center.getX()+”, “+center.getY()+”)”);

}

}

Point.java

public class Point

{

private int x;

private int y;

public int getX() {

return x;

}

public void setX(int x) {

this.x = x;

}

public int getY() {

return y;

}

public void setY(int y) {

this.y = y;

}

}

Spring.xml

<beans xmlns:aop=”http://www.springframework.org/schema/aop" xmlns:p=”http://www.springframework.org/schema/p" xmlns:security=”http://www.springframework.org/schema/security" xmlns:tx=”http://www.springframework.org/schema/tx" xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance" xmlns=”http://www.springframework.org/schema/beans" xsi:schemalocation=”http://www.springframework.org/schema/beans">

<bean class=”com.spring.learning.Triangle” id=”triangle”>

<property name=”pointA” ref=”pointA”></property>

<property name=”pointB” ref=”pointB”></property>

<property name=”pointC” ref=”pointC”></property>

</bean>

<bean class=”com.spring.learning.Circle” id=”circle”>

<property name=”center” ref=”center”></property>

</bean>

<bean class=” com.spring.learning.Point” id=”pointA”>

<property name=”x” value=”0"></property>

<property name=”y” value=”0"></property>

</bean>

<bean class=” com.spring.learning.Point” id=”pointB”>

<property name=”x” value=”-20"></property>

<property name=”y” value=”0"></property>

</bean>

<bean class=” com.spring.learning.Point” id=”pointC”>

<property name=”x” value=”20"></property>

<property name=”y” value=”0"></property>

</bean>

<bean class=” com.spring.learning.Point” id=”center”>

<property name=”x” value=”10"></property>

<property name=”y” value=”10"></property>

</bean>

</beans>

DrawingApp.java

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DrawingApp {

public static void main(String[] args)

{

ApplicationContext context= new ClassPathXmlApplicationContext(“spring.xml”);

Shape shape = (Shape) context.getBean(“triangle”);

shape.draw();

}

}

by Disha Saxena and Kshitiz Mohan.