Top 10 spring interview questions and their answers. Spring basic concepts.

Spring framework is the most recognized framework in java right now . So if you are thinking about changing job in java profile spring framework knowledge is must . Spring IOC and spring-mvc are two hot topics of any interviewer in java these days .The basic categorisation any interviewer will do in front of any interviewee will be :

  1. spring IOC
  2. Dependency Injection
  3. spring security
  4. spring mvc
  5. spring AOP


some less recognized topics also like spring jdbc , spring  JMS but they can be only ask by person who seriously worked on them.  Let’s start with spring IOC and dependency injection first.

Top10  spring interview questions and their answers

Question 1 : What is Dependency Injection

Answer :  Mostly every interviewer start interview this question of spring if he requires spring knowledge in a candidate. As it is explained by name when you injecting dependency of one  java object into another java object that is called dependency injection. Then interviewer  will ask Do I need spring framework for dependency injection then answer is  No.  We were doing it since java started with association of one java object into another that is also dependency injection . Then why do, I need spring for dependency injection. We do not need spring framework for dependency injection we need it for Inversion of control . Means without spring we need to initialize our associated class(injected) class with new   keyword of java but with spring framework is doing this for us. Now he will think that you know basic fundamental of spring at least.

Question 2 : What is Inversion of control as you mentioned in your answer and how spring is defining object for us without using new keyword.

Answer :  Now you will say that spring took control in his hand of creating object and that is called inversion of control. Second how spring is doing it . Spring took definition in xml or in annotation from us that at runtime which object is need to be injected in which one at runtime and create that object using reflection at time of container loading.

Question 3 : What is the benefit I got using spring , I could used new keyword what is the issue with that.

Answer :  Now you will explain it by writing a code below.

You will say if I have an interface called PET .

Interface Pet{}

Now I have an implementation class Dog having name as “pet” (In annotation or XML where bean is defined ) for this Pet interface.

@Named("pet")Class Dog{}

Now I have one object called Manav and this manav has a pet as dog.

Class Manav{
private Pet pet;

Now spring will define Dog object for Pet interface at runtime. But if we were using new keyword we have to define pet  = new Dog(); inside manav and in future manav does not need Dog he need Cat now then we have to replace Dog with Cat in code everywhere but with help of spring  we will remove @named(“pet”) from Dog class and put it at Cat class like below.

Class Cat{}

and spring will initialized Pet which Manav have with cat implementation without changing any code. Now he will be satisfied that you know why we are using spring IOC.

Question 4 : What are different type of IOC.

Answer :  Two types of IOC are present in spring.

  1. Constructor Based : When container called constructor with number of arguments and use that constructor to set associated objects  value with help of those arguments.
  2. Setter Based : Setter based DI happened when container call different setter methods of associated objects to initialize those objects if a non augmented constructor found in that bean.
  3. Field Injection : Field injection happen when we define @inject on field and does not want to define it’s setter and getter . Then spring container assign value to these fields directly through reflection without calling any method.


Question 5 : What are different stages of a bean(Life of a bean).

Answer :  Below steps are followed.

  1. Container will look bean definition in xml or annotations and initialize that bean through reflection.
  2. If an augmented constructor is found then it will call that constructor based on arguments given in beans.xml or else call their setter methods that is also based on beans.xml .
  3. If somebody used annotation then container will look out for annotated associated objects in that bean and initialize them according to their implementations.
  4. If a BeanPostProcessor is attached with that bean then container will call overridden processBeforeInitialization() method .If an init() method is specified then it will call. If a method with nay name but having @postprocessor annotation is present then it will be called.
  5. Now bean will be in container until container will feel that there is no live reference using this bean and let java garbage collector collect this bean.
  6. If bean has implemented DisposableBean interface then destroy method will be called before this bean will be destroyed. If a method with any name but having @predestroy annotation is present then it will be called.


Question 6 : Difference between BeanFactory and ApplicationContext.

Answer :

A BeanFactory is like a factory class that separate beans configurations ,their dependency from actual code and instantiates the bean whenever needed. XMLBeanFactory is one of the implementation of Beanactory which takes xml file as configuration data and instantiate beans according to that XML file.

BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));

ApplicationContext is same like BeanFactory except it have some more features like. It supports multiple files as config XML. It supports bean life cycle events. It supports internationalization etc.

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/application-context.xml");

ApplicationContext is preferred way to use spring but if project require only basic functionality of spring then BeanFactory can also be used.

Question 7 : Why beans are singleton in spring. Does it make them thread unsafe.

Answer :  Beans are singleton in spring . Well if we are using beans as functionality exposures( Means services who are exposing their methods) then it will not be thread safe but if we are using beans as data carriers and trying to modifying or performing some operation on that data then it is not thread safe. For that kind of functionality we should use prototype bean or commonpool functionality of spring.

Question 8 : In how many ways, we can provide configuration data to Spring.

Answer :  We can provide configuration data in three ways to spring framework so that spring can instantiate and inject beans into each other when required.

  1. XML based configuration(Beans.xml)
  2. Annotation based configuration(@autowired/@resources etc.)
  3. Java based configuration(@inject,@named)

Question 9 : What is XML based configuration and it’s example.

Answer :  In spring we can configure beans definition and their dependency on each other in XML files and register those files with help of BeanFactory or ApplicationContext while making application up as I explained above.

<beans xmlns=""    xmlns:xsi=""    xsi:schemaLocation="">    <!-- A simple bean definition -->   <bean id="..." class="...">       <!-- collaborators and configuration for this bean go here -->   </bean></beans>

Question 10 : What is Annotation and Java based configuration and it’s example.

Answer :  In spring we can configure beans definition and their dependency on each other in java source code with help of annotations. These annotations are of two types .

  1. Spring Based : These annotations are given by spring and present in spring framework jars .They can only be used when spring framework is present in application. These annotations majorly are
    @component(To define  a unique name for bean)
    @autowwired(To autowire bean into another bean)
    @resource(To define implementation of this bean which need to bean injected at object creation it match this with @component).
  2. Java Based : These are given by java and can be used with any inversion of control framework. Noo dependency on spring. These annotations majorly are
    @named(To define unique name)
    @inject(To inject bean into another).

Other related posts are :
String interview questions and answers
String vs StringBuffer vs StringBuilder
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Logback logs are not working. Log4j logs are not working. Steps to make logging work.

Please share these posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.


JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming

When you do not want only hibernate sequence to generate primary key of your all tables then you have three options given by JPA and Hibernate .

  1. Sequence Generator
  2. Identity Column
  3. Table Sequence

Let’s talk about Sequence generator and it’s proper use so that it won’t give you Odd and Negative Numbers as your primary key .

Sequence Generator : To use a specific named sequence object (whether it is generated by schema generation or already exists in the database) you must define a sequence generator using a @SequenceGenerator annotation. In this you provide a unique name as name tag, provide database sequence name in sequenceName tag.You can define sequencegenerator at top of class or field both. To use this sequenceGenerator you need to define @Generatedvalue tag with stratgeyType as sequence and sequenceGenerator name on field for which you want this value to be assigned.
Refer below code.

public class Inventory implements Serializable {

private long id;

We have learn how to use sequence generator but still there is possibility of Odd and Negative Numbers as primary key values.

It will happen when database sequence is already exist in database and you are not defining database through hibernate.
How it is happening: Well JPA have allocationSize tag in Sequencegenerator , value of allocationSize is 50 by default if you have not assigned any value. So when Jpa persist that record and demand sequence value from database, it treat that database sequence has incremented that value by 50 so it will substract 50 from that value and try to persist record with that value.
On the other hand database is incrementing value by it’s increment by syntax given at time of it’s defination . Which is not guaranteed to be increment by 50. So there is a possibility of value mismatch and odd value generation which could give you integrityconstraintviolation exception.
So to avoid this problem you need to define allocationSize equal to increment by of database sequence or as 1.Refer below code.

@SequenceGenerator(name="InvSeq",sequenceName="INV_SEQ", allocationSize=1)
private long id;

If you find this post useful please follow,comment and share it.Please feel free to ask questions if you have any.

Other Related Posts :

Set datasource spring bean properties dynamically if server is not available
Logback logs are not working. Log4j logs are not working. Steps to make logging work.
MQ connection not closed and giving MQ Error-2009

Logback logs are not working. Log4j logs are not working. Steps to make logging work.

Logs are not working in application even jar is present in application is the very common problem faced by mostly every java developer .Steps to tackle and solve this problem is what i am going to share today.

Mostly problems come as :
1. Logs were working with previous version of server but not working after upgrade.
2. Log4j logs are not working.
3. Logback logs are not working. etc.

Steps to tackle these problems.

Step 1 : First check if respected jars are present in your application.
Jars for log4j : log4j-api.jar,log4j-core.jar
Jars for logback : logback-core.jar,logback-classic.jar,sl4j.jar

Step 2 : Now if logs are not still working then there is possibilty that your server have these jars with some other implementation.
For eg : Weblogic server have sl4j.jar with jcl logging. So inspite of having jar in your application logback logs will not work.
To solve this problem you can easily find out on google that how to reference application jar in weblogic or how to reference application jar in websphere etc.

If the problem still persist then you need to go to step-3;

Step 3 : Now the problem could be that jar are getting picked up from application but some other jar is also having the same package or server is still picking jars from it’s own directory. To find out that which jar server is picking up use below code in one class and try to call that method somehow to execute below code.

System.out.println(“printing class paths–>”+Logger.class.getProtectionDomain().getCodeSource().getLocation().toURI().toString());
System.out.println(“printing class paths–>”+LoggerFactory.class.getProtectionDomain().getCodeSource().getLocation().toURI().toString());
System.out.println(“printing class paths–>”+StaticLoggerBinder.class.getProtectionDomain().getCodeSource().getLocation().toURI().toString());
catch(Exception e){
System.out.println(“Error in printing class paths”);

Above code is for logback logs and the classes used in this code are classes used for logback logging so you can change according to your logging. What this code is doing that it is printing location of a particular class that from which jar and from which location this class is getting picked up at runtime.

After this you will get your answer that which jar you need to concentrate oor remove from your application to make your logging work.

Please add comments and share if you find it useful or point out mistakes if you find any.

Some other useful post are :

Set datasource spring bean properties dynamically if server is not available
MQ connection not closed and giving MQ Error-2009

Set datasource spring bean properties dynamically if server is not available

Hi Readers today i want to share with you guys something that i faced recently.

Problem :

Recently i was developing a spring application in which container need to initialized by public static void main method rather then any server .
We want user to enter details with swing ui and do not want to save them in properties file at run time. Risk in this is, that anybody can look into properties file which is a security threat.
So now the question is that how we will tell spring container to which DataBase it needs to connect with.

Solution :

So to solve this problem, I created a class which extends BasicDatasource as code given below.

public class CustomDatasource extends BasicDatasource {

private static String hostName;
private static String dbName;
private static String port;
private static String userName;
private static String dbPassword;

private CustomDatasource(){

public static String getHostName() {
return hostName;

public static void setHostName(String hostName) {
CustomDatasource.hostName = hostName;

public static String getDbName() {
return dbName;

public static void setDbName(String dbName) {
CustomDatasource.dbName = dbName;

public static String getPort() {
return port;

public static void setPort(String port) {
CustomDatasource.port = port;

public static String getUserName() {
return userName;

public static void setUserName(String userName) {
CustomDatasource.userName = userName;

public static String getDbPassword() {
return dbPassword;

public static void setDbPassword(String dbPassword) {
CustomDatasource.dbPassword = dbPassword;

Now make this class as datasource bean in Beans.xml and inject this bean into persistanceUnitManager .
Now initialize spring container as given below.

public class Test {
public static void main(String args[]){
Scanner in = new Scanner(;
System.out.println("Enter a string");
String dbName = in.nextLine();
String hostName = in.nextLine();
String port = in.nextLine();
String userName = in.nextLine();
String dbPassword = in.nextLine();
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/Beans.xml");

Now without saving database configuration in any properties file your application will be able to connect with database.

Other related posts are :
HTML to PDF conversion in JAVA | HTML to PDF example in JAVA
Top 10 spring interview questions and their answers. Spring basic concepts.
MQ connection not closed and giving MQ Error-2009
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming

Please share this posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.

MQ connection not closed and giving MQ Error-2009

Problem :

Sometimes MQ connection does not close even after calling close method. It gives us MQ Error code-2009. I found out solution for this problem after a long struggle and hit & try, so i thought to share it with everyone.

Solution :

What most people do the mistake is that they close queue connection before queue manager connection. When you close queue connection first then it made queue manager connection unavailable and open inspite of firing disconnect method on queue manager connection after queue close. IBM MQ close these open connections self but when you create connection very frequently before MQ close them and eventually it gives you 2009 error. So always close queue manager before queue connection.

Other related posts are :
Top 10 spring interview questions and their answers. Spring basic concepts.
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Set datasource spring bean properties dynamically if server is not available

Please share these posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.