<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" gd:etag="W/&quot;CkAMQ3Y8fip7ImA9WhRaFEg.&quot;"><id>tag:blogger.com,1999:blog-35897879</id><updated>2012-02-16T19:53:02.876-08:00</updated><category term="Java CV tips" /><category term="Seam interview questions" /><category term="general career tips" /><category term="Java Web Service Interview Answers" /><category term="design patterns" /><category term="Architecture" /><category term="SQL" /><category term="Java/J2EE Interview Questions" /><category term="mock objects" /><category term="user defined key class" /><category term="Seam" /><category term="Java interview tips" /><category term="Dependency Injection" /><category term="Selenium" /><category term="Web Service Interview Answers" /><category term="Java coding interview questions and answers" /><category term="job hunting tips" /><category term="JSF Interview Questions" /><category term="HIbernate Interview Questions" /><category term="Java interview answers pdfs" /><category term="Java tools" /><category term="Maven interview questions" /><category term="Java interview questions pdfs" /><category term="build tools" /><category term="Core Java Career Essentials Book Details" /><category term="Hibernate interview answers" /><category term="Core Java Career Essentials" /><category term="Java J2EE Interview Companion" /><category term="Maven vs ANT" /><category term="Free Book PDFs on Java Career" /><category term="Java Collection Interview Questions and Answers" /><category term="UNIX interview answers" /><category term="IOC" /><category term="truststore" /><category term="changing jobs" /><category term="SSL" /><category term="Spring" /><category term="JSP INterview Answers" /><category term="RESTful Web service Answers" /><category term="Java resume tips" /><category term="JSF Interview Questions and Answers" /><category term="design patterns interview questions" /><category term="java career tips" /><category term="Web Service Interview Questions" /><category term="Servlets" /><category term="JMeter" /><category term="Java/J2EE CV or Resume tips:" /><category term="UNIX interview questions" /><category term="Java Web Service Interview Questions" /><category term="Spring interview questions" /><category term="Comple-time versus runtime" /><category term="security" /><category term="enterprise java interview questions" /><category term="SQL Interview" /><category term="Selenium and Web driver" /><category term="Java/JEE Interview Questions and Answers Book Details" /><category term="Java multithreading interview questions and answers" /><category term="Design" /><category term="CV tips" /><category term="Hibernate interview questions and answers" /><category term="SQL Interview Questions" /><category term="feeling stagnated" /><category term="Java interview" /><category term="properties" /><category term="multi-threading interview questions" /><category term="DI" /><category term="SQL Interview Answers" /><category term="java interview questions" /><category term="java interview answers" /><category term="Java OO Interview Questions and Answers" /><category term="Maven" /><category term="JSF Interview Answers" /><category term="code quality" /><category term="Resume tips" /><category term="Java/JEE Resume Companion Book Details" /><category term="performance testing" /><category term="unit testing" /><category term="JEE interview questions" /><category term="RESTful Web Service Questions" /><category term="JSF" /><category term="JavaScript interview answers" /><category term="Spring interview answers" /><category term="Spring Interview Questions and Answers" /><category term="JavaScript interview questions" /><category term="Ant" /><category term="keystore" /><category term="JSP Interview Questions" /><category term="Java J2EE fundamentals" /><title>400+ Java Interview Questions and Answers</title><subtitle type="html">for Java job seekers and interviewers. Around 650 Java and JEE interview questions are answered clearly and concisely with lots of diagrams, examples, code snippets, and 14+ key areas through Java career companions and essentials. This includes 150+ FAQs, 80+ open-ended, and 100+ coding questions and answers for you to take the road less traveled if you are an interviewee and to hire the candidate(s) with the right caliber if you are an interviewer.</subtitle><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://java-success.blogspot.com/" /><link rel="next" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default?start-index=26&amp;max-results=25&amp;redirect=false&amp;v=2" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>69</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/Java/JEECareerCompanion" /><feedburner:info uri="java/jeecareercompanion" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId>Java/JEECareerCompanion</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><entry gd:etag="W/&quot;A0YCR3k5eSp7ImA9WhRaEUw.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-1747298545183598930</id><published>2015-09-28T21:34:00.000-07:00</published><updated>2012-02-12T23:46:06.721-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-02-12T23:46:06.721-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="JEE interview questions" /><category scheme="http://www.blogger.com/atom/ns#" term="java interview questions" /><category scheme="http://www.blogger.com/atom/ns#" term="Java interview" /><category scheme="http://www.blogger.com/atom/ns#" term="java interview answers" /><title>400+ Java Interview Questions and Answers with lots of diagrams, examples, &amp; code</title><content type="html">&lt;div style="text-align: center;"&gt;&lt;span style="color: #0b5394;"&gt;&lt;/span&gt;&lt;/div&gt;&lt;div style="color: #783f04;"&gt;&lt;h4&gt;&lt;span style="color: green; font-size: 1em;"&gt;&lt;span style="font-size: large;"&gt;Free PDF downloads:&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/h4&gt;&lt;h4&gt;&lt;span style="color: green; font-size: 1em;"&gt;&lt;span style="font-size: large;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;/h4&gt;&lt;div style="color: black;"&gt;&lt;b&gt;&lt;span style="font-size: small;"&gt;Core Java and enterprise Java&amp;nbsp; Interview Questions and Answers:&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;&lt;/div&gt;&lt;ul&gt;&lt;li&gt; &lt;span style="font-size: small;"&gt;&lt;a href="http://www.lulu.com/items/volume_62/436000/436862/3/preview/print/PREVIEW_JAVA_J2EE_BOOK.pdf" target="_blank"&gt;400+ Questions and Answers:&amp;nbsp; Java/J2EE Job Interview Companion (47 pages)&lt;/a&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;ul&gt;&lt;li&gt; &lt;span style="font-size: small;"&gt;&lt;a href="http://www.lulu.com/items/volume_71/10993000/10993464/2/print/CoreJavaCareerEssentialsInteriorCSFinal-preview.pdf" target="_blank"&gt;250+ Questions and Answers: Core Java Career  Essentials (107 pages)&lt;/a&gt;&lt;/span&gt; &lt;/li&gt;
&lt;/ul&gt;&lt;div style="color: #38761d;"&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style="color: black;"&gt;&lt;b&gt;&lt;span style="font-size: small;"&gt;Java/J2EE Resume/CV sample PDF&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;&lt;ul&gt;&lt;li&gt;&lt;span style="font-size: large;"&gt;&lt;b&gt; &lt;/b&gt;&lt;span style="color: black;"&gt;&lt;span style="font-size: small;"&gt;&lt;span style="font-size: large;"&gt;&lt;span style="font-size: small;"&gt;&lt;b&gt;&lt;a href="http://www.lulu.com/product/ebook/javajee-resume-companion-%2819-pages%29/4375463" target="_blank"&gt;Java/J2EE Resumes (19 pages)&lt;/a&gt;&lt;/b&gt;&lt;/span&gt; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;div class="separator" style="clear: both; text-align: left;"&gt;&lt;br /&gt;
&lt;/div&gt;&lt;br /&gt;
&lt;span style="font-size: small;"&gt;Find the Java Interview books and complete PDFs at&amp;nbsp;&lt;a href="http://www.lulu.com/spotlight/java_success" target="_blank"&gt;Lulu.com&lt;/a&gt; and &lt;a href="http://www.amazon.com/Arulkumaran-Kumaraswamipillai/e/B002IW7CZ4/ref=ntt_dp_epwbk_0" target="_blank"&gt;Amazon.com&lt;/a&gt;.&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This blog compliments the above resources by serving as a very handy refresher and a quick reference material. Covers everything from Core Java to enterprise Java, JavaScript to Unix and many development tools to sought-after frameworks like Spring, Hibernate, and JSF with &lt;span style="font-size: large;"&gt;lots of diagrams&lt;/span&gt;, &lt;span style="font-size: large;"&gt;code snippets&lt;/span&gt;, and &lt;span style="font-size: large;"&gt;examples&lt;/span&gt;. If you just want to cram the answers prior to job interviews, this&lt;b&gt; &lt;/b&gt;is&lt;b&gt; NOT&lt;/b&gt; for YOU.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color: #38761d; font-size: large;"&gt;This blog covers and compliments our books with&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;b&gt;&lt;a href="http://java-success.blogspot.com.au/p/core-java.html"&gt;Core Java&lt;/a&gt; &lt;/b&gt;to&lt;b&gt;&lt;a href="http://java-success.blogspot.com.au/p/jee-q.html"&gt; Enterprise Java&lt;/a&gt;&lt;/b&gt; Interview Questions and Answers&lt;/li&gt;
&lt;li&gt;Most frequently asked Interview Questions and Answers on &lt;b&gt;&lt;a href="http://java-success.blogspot.com.au/p/more-q.html"&gt;scripting languages&lt;/a&gt;&lt;/b&gt; like&amp;nbsp; &lt;b&gt;&lt;a href="http://java-success.blogspot.com.au/2012/01/javascript-interview-questions-and.html"&gt;JavaScript&lt;/a&gt; &lt;/b&gt;and &lt;b&gt;&lt;a href="http://java-success.blogspot.com.au/2012/01/unix-interview-questions-and-answers.html"&gt;Unix&lt;/a&gt;&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;Popular questions and answers on sought after frameworks like&lt;b&gt; &lt;a href="http://java-success.blogspot.com.au/2011/10/jsf-interview-questions-and-answers.html"&gt;JSF&lt;/a&gt;&lt;/b&gt;, &lt;b&gt;&lt;a href="http://java-success.blogspot.com.au/2011/10/spring-interview-questions-and-answers.html"&gt;Spring&lt;/a&gt;&lt;/b&gt;, and &lt;b&gt;&lt;a href="http://java-success.blogspot.com.au/2010/12/hibernate-interview-questions-q.html"&gt;Hibernate&lt;/a&gt;&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;Most popular &lt;b&gt;&lt;a href="http://java-success.blogspot.com.au/p/open-q.html"&gt;open-ended &lt;/a&gt;&lt;/b&gt;questions and answers on tools to improve developer productivity and code quality.&lt;/li&gt;
&lt;li&gt;And a lot more. Use the search box on the right hand side panel for specific key words. &lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
Hope these resources add value to you as it did to me to go from being a Mechanical Engineer to a Java/JEE based development team leader in 4 years and then to become an independent contractor/consultant working for multinational organizations in varying capacities. Stay tuned or connected for more handy resources. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;h4&gt;&lt;span style="color: green; font-size: 1em;"&gt; &lt;span style="font-size: large;"&gt;What do others say: &lt;/span&gt;&lt;/span&gt;&lt;/h4&gt;&lt;table bgcolor="#F5FFFA" cellspacing="10"&gt;&lt;tbody&gt;
&lt;tr&gt;    &lt;td width="50%"&gt;"After landing a job I have kept on&lt;a class="cssButton" href="javascript:void(0)" id="publishButton" target=""&gt;&lt;/a&gt;&lt;br /&gt;
&lt;div class="cssButtonOuter"&gt;&lt;div class="cssButtonMiddle"&gt;&lt;div class="cssButtonInner"&gt;&lt;a class="cssButton" href="javascript:void(0)" id="publishButton" target=""&gt;Publish Post&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;reading the book and recommend it to all my friends..." -- &lt;a href="http://www.coderanch.com/t/32756/Jobs/careers/Interview-Book-Java-EE-Job" target="_blank" title="Java J2EE Interview"&gt;JavaRanch Forum&lt;/a&gt;&lt;/td&gt;    &lt;td width="50%"&gt;"I have read several technical books over the last few years, but this one was entirely different...." - &lt;a href="http://books.dzone.com/reviews/javaj2ee-job-interview-compani" target="_blank" title="Java J2EE Interview"&gt;By Meera Subbarao &lt;b&gt;IT Book Zone Team Leader&lt;/b&gt;&lt;/a&gt;&lt;/td&gt;   &lt;/tr&gt;
&lt;tr&gt;    &lt;td width="50%"&gt;I can safely say you'd have to buy probably at least 15 individual books and supplement... -- &lt;a href="http://www.amazon.co.uk/review/product/1411668243/ref=dp_top_cm_cr_acr_txt/279-1064603-7079630?%5Fencoding=UTF8&amp;amp;showViewpoints=1" target="_blank" title="Java J2EE Interview"&gt;By Mr. Jeremy&lt;br /&gt;
Flowers at &lt;b&gt;Amazon UK&lt;/b&gt;&lt;/a&gt;&lt;/td&gt;    &lt;td width="50%"&gt;"I was in the course of reading the book and now that I have&lt;br /&gt;
finished it thoroughly , i'm 100% sure i will crack the next interview" -- &lt;a href="https://www.blogger.com/comment.g?blogID=35897879&amp;amp;postID=3580825666245419385" target="_blank"&gt;Blog comment&lt;/a&gt;&lt;/td&gt;   &lt;/tr&gt;
&lt;tr&gt;    &lt;td width="50%"&gt;"If a person manages to give answers as given in book,&lt;br /&gt;
he/she can easily bag a new job..." -- &lt;a href="http://www.coderanch.com/t/424400/Jobs/careers/Interview-Book-Java-EE-Job" target="_blank" title="Java J2EE Interview Questions &amp;amp; Answers"&gt;&lt;br /&gt;
JavaRanch forum&lt;/a&gt;&lt;/td&gt;       &lt;td width="50%"&gt;"Very well written! authors have good, clear style" I'm happy to say I know almost all of the content in the book already, but I'm still very happy I bought it. What really jumped out at me is how well written the explanations are. There are so many book out&lt;br /&gt;
there that get quite pompous and long-winded with their explanations of polymorphism, for instance. But the authors have summarize what polymorphism does in one short, clear sentence early on in the book. Most of the other explanations are similar, they really "cut through the crap" and provide the most direct answer possible. I recommend this book as a refresher for any Java professional--inevitably, we all get tied up in the peculiar...." -- &lt;a href="http://www.lulu.com/product/paperback/javaj2ee-job-interview-companion---400%2b-questions-answers/805814" target="_blank" title="Java J2EE Interview Questions &amp;amp; Answers"&gt;&lt;br /&gt;
Lulu.com reviews&lt;/a&gt;&lt;/td&gt;   &lt;/tr&gt;
&lt;tr&gt;    &lt;td width="50%"&gt;"If you have read the The Pragmatic Programmer: From Journeyman to Master, you would enjoy this book too. Is similar about the comfortable pleasure to read this book."&amp;nbsp; &lt;a href="http://java.dzone.com/reviews/core-java-career-essentials" target="_blank" title="Java Interview Questions &amp;amp; Answers"&gt;IT Book Zone Review&lt;/a&gt;&lt;/td&gt;    &lt;td width="50%"&gt;&lt;/td&gt;   &lt;/tr&gt;
&lt;/tbody&gt; &lt;/table&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: left;"&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: left;"&gt;&lt;a href="http://1.bp.blogspot.com/-9Q5rPdhJi_Y/Topl4-9QPbI/AAAAAAAAAGg/ZTuBA-7uXlg/s1600/CareerOptions_000.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;span style="color: #6aa84f;"&gt;&lt;span style="font-size: large;"&gt;Why prepare?&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;/a&gt; &lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-9Q5rPdhJi_Y/Topl4-9QPbI/AAAAAAAAAGg/ZTuBA-7uXlg/s1600/CareerOptions_000.jpg" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="239" src="http://1.bp.blogspot.com/-9Q5rPdhJi_Y/Topl4-9QPbI/AAAAAAAAAGg/ZTuBA-7uXlg/s320/CareerOptions_000.jpg" width="320" /&gt;&lt;/a&gt;&lt;a href="http://1.bp.blogspot.com/-9Q5rPdhJi_Y/Topl4-9QPbI/AAAAAAAAAGg/ZTuBA-7uXlg/s1600/CareerOptions_000.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;/a&gt; &lt;/div&gt;&lt;div style="text-align: center;"&gt;&lt;b&gt;&lt;span style="color: #b45f06;"&gt;Preparation breeds confidence and confidence breeds success.&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;&lt;br /&gt;
Preparation can help you communicate your thoughts more clearly with examples and illustrations. Preparing prior to each interview has immensely helped me fast-track my career. Even with 11+ years of hands-on experience in Java/JEE based design and development, I still brush up on the fundamentals and the 14+ key areas using the career companions and the essentials prior to attending&amp;nbsp; job interviews or important meetings.&lt;br /&gt;
&lt;br /&gt;
Preparation has always resulted in multiple job offers and much needed job security as a freelancer even in a much tougher job market. Understanding &lt;b&gt;what problems are faced by the industry&lt;/b&gt; and &lt;b&gt;what the prospective employers are looking for&lt;/b&gt; can make a huge difference to one's career. Being in this know how can also open more doors to take on more challenging tasks in varying capacities. This blog and books share my experience. It is quite encouraging from many personal emails and review comments as to how these materials have helped many others. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color: #6aa84f; font-size: large;"&gt;How do these resources help you fast-track your Java career?&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
If you rely only on your own experience, it will take you a lot longer to get a good handle on these 14+ key areas. The best way to fast-track your career is to pro-actively learn these 14+ key areas from others' experience, good books and online articles, and apply what you had learned to practice. This will help you earn a reputation as a "&lt;b&gt;go to person"&lt;/b&gt; through your contributions and achievements at work.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div style="color: #6aa84f;"&gt;&lt;span style="font-size: large;"&gt;What are these 14+ key areas?&amp;nbsp;&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-ZBjdrdCgOtI/ToP21q2ZRKI/AAAAAAAAAE0/VhomqbTD-WI/s1600/key_areas_14_plus.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="160" src="http://3.bp.blogspot.com/-ZBjdrdCgOtI/ToP21q2ZRKI/AAAAAAAAAE0/VhomqbTD-WI/s640/key_areas_14_plus.JPG" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;ol&gt;&lt;li&gt;Language Fundamentals (&lt;b&gt;LF&lt;/b&gt;)&lt;/li&gt;
&lt;li&gt;Specification Fundamentals (&lt;b&gt;SF&lt;/b&gt;)&lt;/li&gt;
&lt;li&gt;Platform Fundamentals (&lt;b&gt;PF&lt;/b&gt;)&lt;/li&gt;
&lt;li&gt;Design Considerations&amp;nbsp; (&lt;b&gt;DC&lt;/b&gt;)&lt;/li&gt;
&lt;li&gt;Design Patterns (&lt;b&gt;DP&lt;/b&gt;)&lt;/li&gt;
&lt;li&gt;Concurrency Management (&lt;b&gt;CM&lt;/b&gt;) &lt;/li&gt;
&lt;li&gt;Performance Considerations&amp;nbsp; (&lt;b&gt;PC&lt;/b&gt;)&lt;/li&gt;
&lt;li&gt;Memory/Resource Considerations&amp;nbsp; (&lt;b&gt;MC&lt;/b&gt;) &lt;/li&gt;
&lt;li&gt;Transaction Management&amp;nbsp; (&lt;b&gt;TM&lt;/b&gt;)&lt;/li&gt;
&lt;li&gt;Security (&lt;b&gt;SE&lt;/b&gt;)&lt;/li&gt;
&lt;li&gt;Scalability&amp;nbsp; (&lt;b&gt;SC&lt;/b&gt;)&lt;/li&gt;
&lt;li&gt;Best Practices (&lt;b&gt;BP&lt;/b&gt;)&lt;/li&gt;
&lt;li&gt;Coding (&lt;b&gt;CO&lt;/b&gt;)&lt;/li&gt;
&lt;li&gt;Exception Handling (&lt;b&gt;EH&lt;/b&gt;) &lt;/li&gt;
&lt;li&gt;Software Development Processes (&lt;b&gt;SDP&lt;/b&gt;) &lt;/li&gt;
&lt;li&gt;Quality of Service&amp;nbsp; (&lt;b&gt;QoS&lt;/b&gt;)&lt;/li&gt;
&lt;/ol&gt;&lt;br /&gt;
&lt;div style="color: #6aa84f;"&gt;&lt;span style="font-size: large;"&gt;Why use these resources?&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div style="color: #990000; text-align: center;"&gt;&lt;span style="font-size: large;"&gt;&lt;b&gt;&lt;span style="font-size: small;"&gt;Standout from the candidates who are more qualified than you are&lt;/span&gt;&lt;/b&gt;&lt;/span&gt;&lt;/div&gt;&lt;span style="font-size: large;"&gt;&lt;b&gt;&lt;span style="color: #660000; font-size: small;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/b&gt;&lt;/span&gt; &lt;br /&gt;
The resources provided in here are full of &lt;span style="color: black; font-size: small;"&gt;practical examples&lt;/span&gt;&lt;span style="font-size: small;"&gt;,&lt;/span&gt; &lt;span style="font-size: small;"&gt;diagrams&lt;/span&gt;, &lt;span style="font-size: small;"&gt;code snippets&lt;/span&gt;, and cross references to provide clear and concise answers to most of the very frequently asked Java interview questions.&lt;br /&gt;
&lt;br /&gt;
Each question is tagged with one or more of the &lt;span style="font-size: small;"&gt;14+ key areas&lt;/span&gt;.  These questions and answers are not just meant for cramming prior to  interviews. If you are after real career success, pro-actively apply  what you learn from these resources.&lt;br /&gt;
&lt;br /&gt;
The questions and answers approach also give a different perspective to clearing up your fundamentals in Java. The answers are  detailed enough to learn the fundamentals while preparing for job  interviews, code review sessions and technical team meetings. Depending  on your level of experience, some answers may require additional  research on Google to get a better understanding.&lt;br /&gt;
&lt;br /&gt;
Good  caliber professionals are promoted and paid well for thinking,  reasoning, solving business problems, and getting things done by drawing on their experiences and skills&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;to look  at the big picture.&lt;/li&gt;
&lt;li&gt;to pay attention to details.&lt;/li&gt;
&lt;li&gt;for applying the  fundamentals/key areas to solve business problems.&lt;/li&gt;
&lt;li&gt;for complimenting their technical "know how" with  good soft skills and attitude to get things done.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;div style="color: #6aa84f;"&gt;&lt;span style="font-size: large;"&gt;Should you get certified in Java?&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
Certifications combined with many other "know hows" can make  you a better programmer. At the end of the day, it is &lt;b&gt;what you know &lt;/b&gt;and &lt;b&gt;can do &lt;/b&gt;makes the real difference and  not what some documents declare what you know. Certified or not, you will be grilled in job interviews. In my view, &lt;b&gt;favor continuous learning &lt;/b&gt;and &lt;b&gt;hands-on  experience&lt;/b&gt;. Learn more here &lt;a href="http://java-success.blogspot.com/2010/11/why-certifications-are-alone-not-enough.html" target="_blank"&gt;Why Java certifications are alone not enough?&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div style="color: #6aa84f;"&gt;&lt;span style="font-size: large;"&gt;How do you get your first break with Java?&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
In summary, the best way for people to get their first break with Java is to:&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Learn the core concepts and work on a Java programming project. Start a little Java-based project of your own.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Participate in an open-source project - even if it's just submitting a little patch to see how things fit together.&lt;/li&gt;
&lt;li&gt;Update your resume based on the experience and skills you acquired in the above steps to get a break by acquiring an entry level job, even volunteer work should help you open more doors. More on this here -- &lt;a href="http://java-success.blogspot.com/2010/12/handy-tips-to-get-some-work-experience.html"&gt;How to get the much needed experience in Java?&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;b&gt;Note: &lt;/b&gt;Even though the certifications can be useful, don't wait until you've passed certifications before trying to get work. Recruiters don't hire just because someone has a certification. Certified or not, your Java knowledge and experience will be tested at job interviews.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-size: large;"&gt;&lt;span style="color: #6aa84f;"&gt;What Java questions are asked in job interviews?&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-size: small;"&gt;In career forums,&amp;nbsp; many ask for Java interview questions for 2 year experience, 4 year experience, etc. My advise is that if you brush up on the Java/JEE basics and the 14+ key areas, you should be fine&lt;/span&gt;&lt;span style="font-size: small;"&gt;. &lt;/span&gt;&lt;span style="font-size: small;"&gt;You have no control over what questions are going to be asked. The interviews are not technical contests to see who gets most questions right.&lt;/span&gt;&lt;span style="font-size: small;"&gt; It is all about convincing your prospective employer that you can get the job done&lt;/span&gt;&lt;span style="font-size: small;"&gt;. The open-ended questions give you a great opportunity to sell your strengths in these 14+ key areas along with your soft skills, and personal attributes to make a good impression.&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Having said this, there are some very basic "&lt;b&gt;must know&lt;/b&gt;" Java&amp;nbsp; interview questions that can make or break the deal. These "must know" Java interview questions are covered in my books (tagged as &lt;b&gt;FAQ&lt;/b&gt;s) and blog entries along with many open-ended questions and answers. You hold the key to your Java career success, and hope this blog assists in your quest to succeed in your career.&lt;br /&gt;
&lt;br /&gt;
If you have any specific question or would like to provide any constructive criticisms, then contact me via email java-interview@hotmail.com. Hope this blog and books help you take the road less traveled.&lt;br /&gt;
&lt;br /&gt;
&lt;div style="color: #783f04; text-align: center;"&gt;"&lt;b&gt;talk the talk and walk the walk .... &lt;/b&gt;"&amp;nbsp; &amp;nbsp; &lt;/div&gt;&lt;div class="cssButtonOuter"&gt;&lt;div class="cssButtonMiddle"&gt;&lt;div class="cssButtonInner"&gt;&lt;a class="cssButton" href="javascript:void(0)" id="publishButton" target=""&gt;&lt;br /&gt;
&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-size: large;"&gt;&lt;span style="color: #6aa84f;"&gt;What gives the real job security?&lt;/span&gt;&lt;/span&gt; &lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;br /&gt;
There is no such thing as real job security in IT. Keeping your knowledge and skills sharp and current along with good networking, marketing, and soft skills is the best way to achieve real job security. The jobs offered on a contract basis is on the rise, and can be more rewarding for some.&amp;nbsp;&amp;nbsp; &lt;a href="http://www.contractjobs.com/jobs/information-technology/" target="_blank"&gt;contract-jobs-in-IT&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
"&lt;span style="color: #38761d;"&gt;The people who win are not necessarily the  smartest people, but they are the people who are able to sustain drive,  commitment, passion and engagement&lt;/span&gt;" -- by David Maiser &lt;br /&gt;
&lt;br /&gt;
&lt;div style="color: #0b5394; text-align: center;"&gt;&lt;table border="0"&gt;&lt;tbody&gt;
&lt;tr valign="top"&gt;   &lt;td&gt;&lt;br /&gt;
&lt;ul&gt;&lt;span style="color: #006496; font-family: arial; font-size: 0.9em; font-weight: bold;"&gt;
&lt;li style="color: #674ea7;" type="square"&gt;&lt;a href="http://java-success.blogspot.com/2008/08/resume-is-key-marketing-tool-in.html"&gt;Attend more interviews with better Resume/CV&lt;/a&gt;&lt;/li&gt;
&lt;/span&gt;   &lt;/ul&gt;&lt;/td&gt;   &lt;td&gt;&lt;br /&gt;
&lt;ul&gt;&lt;span style="color: orange; font-family: arial; font-size: 0.9em; font-weight: bold;"&gt;
&lt;li style="color: orange;" type="square"&gt;&lt;a href="http://java-success.blogspot.com/2011/09/how-to-prepare-for-javajee-job.html"&gt;Get more job offers with better interview preparation&lt;/a&gt;&lt;/li&gt;
&lt;/span&gt;   &lt;/ul&gt;&lt;/td&gt;   &lt;td&gt;&lt;br /&gt;
&lt;ul&gt;&lt;span style="color: #006496; font-family: arial; font-size: 0.9em; font-weight: bold;"&gt;
&lt;li style="color: #0b5394;" type="square"&gt;&lt;a href="http://java-success.blogspot.com/2007/10/how-to-choose-from-multiple-javaj2ee.html"&gt; Negotiate better salaries/rates with multiple job offers&lt;/a&gt;&lt;/li&gt;
&lt;/span&gt;   &lt;/ul&gt;&lt;/td&gt;   &lt;td&gt;&lt;br /&gt;
&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-1747298545183598930?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/Gg_wPzPExAjbPgU79Jf31KmQAfc/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Gg_wPzPExAjbPgU79Jf31KmQAfc/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/Gg_wPzPExAjbPgU79Jf31KmQAfc/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Gg_wPzPExAjbPgU79Jf31KmQAfc/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/PKdJiFCOPYI" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/1747298545183598930/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=1747298545183598930" title="10 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/1747298545183598930?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/1747298545183598930?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/PKdJiFCOPYI/why-blog-on-java-interview-questions.html" title="400+ Java Interview Questions and Answers with lots of diagrams, examples, &amp; code" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://1.bp.blogspot.com/-9Q5rPdhJi_Y/Topl4-9QPbI/AAAAAAAAAGg/ZTuBA-7uXlg/s72-c/CareerOptions_000.jpg" height="72" width="72" /><thr:total>10</thr:total><feedburner:origLink>http://java-success.blogspot.com/2011/09/why-blog-on-java-interview-questions.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CE8NQH84eip7ImA9WhRaEko.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-5183680927792475996</id><published>2012-02-13T21:12:00.000-08:00</published><updated>2012-02-14T18:28:11.132-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-02-14T18:28:11.132-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Web Service Interview Answers" /><category scheme="http://www.blogger.com/atom/ns#" term="RESTful Web service Answers" /><category scheme="http://www.blogger.com/atom/ns#" term="Web Service Interview Questions" /><category scheme="http://www.blogger.com/atom/ns#" term="RESTful Web Service Questions" /><title>Web Services Interview Questions and Answers - RESTful Web Service Overview</title><content type="html">&lt;b&gt;Q.&lt;/b&gt; Why would you use a RESTful Web service? &lt;br /&gt;
&lt;b&gt;A&lt;/b&gt;. RESTful Web service is easy, straightforward, supports multiple data formats like XML, JSON, etc and easily testable. For example, &lt;br /&gt;
&lt;br /&gt;
It can be tested by&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;1.&lt;/b&gt; Directly invoking the service&amp;nbsp; from the browser by typing a URL if the RESTFul service supports GET request with query parameters. For example,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;http://localhost:8080/executionservices/execution/1.0/order/create?accountId=123&amp;amp;qty=25 
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;2.&lt;/b&gt; You could use a Firefox plugin like "&lt;b&gt;poster&lt;/b&gt;" to post an XML request to your service. &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;3. &lt;/b&gt;You could write a Web Service client to consume the Web service from a test class or a separate application client. You could use libraries like &lt;i&gt;HttpClient&lt;/i&gt;, &lt;i&gt;CXF &lt;/i&gt;Client, &lt;i&gt;URLConnection&lt;/i&gt;, etc to connect to the RESTful service.   &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; What are the various implementations of JAX-RS available to choose from in Java?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; When you're developing with REST in Java, you have a lot of options to choose from in terms of the frameworks. There's &lt;b&gt;Jersey&lt;/b&gt;, the reference implementation from Oracle, then you have &lt;b&gt;RestEasy&lt;/b&gt;, the JBoss choice, and there is &lt;b&gt;CXF&lt;/b&gt;, the Apache choice. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How would you go about implemnting the RESTful Web service using the framework of your choice?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;Let's look at &lt;b&gt;CXF &lt;/b&gt;as it is easy&lt;b&gt; &lt;/b&gt;to configure&lt;b&gt;. &lt;/b&gt;The steps involved include&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Bringing in the relevant framework jar files for Spring and CXF. For example, via Maven using a pom.xml file.&lt;/li&gt;
&lt;li&gt;If the request and responses are XML based POST, then define an XSD file and generate JAXB annotated classes for marshalling and unmarshalling the request and response.&lt;/li&gt;
&lt;li&gt;Define the WebService interface and implementation classes.&lt;/li&gt;
&lt;li&gt;Define any interceptor and filter classes if required to intercept the request and responses for implementing the cross-cutting concerns like security validation, logging, auditing, setting up or initializing the locale, etc&lt;/li&gt;
&lt;li&gt;Wire up the classes via Spring and CXF config files. For example, webservices-config.xml and cxf.xml.&lt;/li&gt;
&lt;li&gt;Finally define the CXF servlet and bootstrap the relevant config files via the web.xml file.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Firstly, configure the maven &lt;b&gt;pom.xml&lt;/b&gt; file to include the relevant jar files.  &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.springframework&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spring-context&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;3.0.5.RELEASE&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.springframework&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spring-web&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;3.0.5.RELEASE&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.apache.cxf&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;cxf-rt-frontend-jaxrs&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;2.2.3&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
Define the request and response objects with JAXB annotations as our Web service payload is XML, hence it needs to be marshalled (i.e. convert from object to XML) and unmarshalled (XML to object). &lt;b&gt;OrderRequest&lt;/b&gt; &amp;amp; &lt;b&gt;OrderResponse &lt;/b&gt;classes can be generated from XSD file &lt;b&gt;OrderRequestResponde.xsd&lt;/b&gt;  shown below.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&amp;gt;
&amp;lt;xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"&amp;gt;

   &amp;lt;xs:complexType name="OrderResponse"&amp;gt;
      &amp;lt;xs:sequence&amp;gt;
         &amp;lt;xs:element name="orderId" type="xs:string" minOccurs="0" /&amp;gt;
         &amp;lt;xs:element name="responseCode" type="responseCode" minOccurs="0" /&amp;gt;
         &amp;lt;xs:element name="accountId" type="xs:string" minOccurs="0" /&amp;gt;
      &amp;lt;/xs:sequence&amp;gt;
   &amp;lt;/xs:complexType&amp;gt;

   &amp;lt;xs:complexType name="OrderRequest"&amp;gt;
      &amp;lt;xs:sequence&amp;gt;
         &amp;lt;xs:element name="accountId" type="xs:string" minOccurs="0" /&amp;gt;
         &amp;lt;xs:element name="quantity" type="xs:int" minOccurs="0" /&amp;gt;
      &amp;lt;/xs:sequence&amp;gt;
   &amp;lt;/xs:complexType&amp;gt;

   &amp;lt;xs:simpleType name="responseCode"&amp;gt;
      &amp;lt;xs:restriction base="xs:string"&amp;gt;
         &amp;lt;xs:enumeration value="SUCCESS" /&amp;gt;
         &amp;lt;xs:enumeration value="FAILED" /&amp;gt;
         &amp;lt;xs:enumeration value="REJECTED" /&amp;gt;
         &amp;lt;xs:enumeration value="UNKNOWN" /&amp;gt;
      &amp;lt;/xs:restriction&amp;gt;
   &amp;lt;/xs:simpleType&amp;gt;

&amp;lt;/xs:schema&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
The .java files can be generated via the &lt;b&gt;xjc&lt;/b&gt; command to generate JAXB annotated classes. The &lt;b&gt;OrderRequest.java&lt;/b&gt;, &lt;b&gt;OrderResponse.java&lt;/b&gt;, &lt;b&gt;ResponseCode.java &lt;/b&gt;and &lt;b&gt;ObjectFactory.java&lt;/b&gt; files are generated under the package "com.myapp.data.order".&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;xjc -d "c:\temp" -p "com.myapp.data.order" "C:\temp\xsd\OrderRequestResponde.xsd" -extension

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Here are the generated files:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;OrderRequest.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.3 in JDK 1.6 
// See &lt;a href="http://java.sun.com/xml/jaxb"&gt;http://java.sun.com/xml/jaxb&lt;/a&gt; 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2012.02.07 at 05:07:31 PM EST 
//


package com.myapp.data.order;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;


/**
 * Java class for OrderRequest complex type.
 * 
 * 
The following schema fragment specifies the expected content contained within this class.
 * 
 * 
&lt;pre&gt;* &amp;lt;complexType name="OrderRequest"&amp;gt;
 *   &amp;lt;complexContent&amp;gt;
 *     &amp;lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&amp;gt;
 *       &amp;lt;sequence&amp;gt;
 *         &amp;lt;element name="accountId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&amp;gt;
 *         &amp;lt;element name="quantity" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/&amp;gt;
 *       &amp;lt;/sequence&amp;gt;
 *     &amp;lt;/restriction&amp;gt;
 *   &amp;lt;/complexContent&amp;gt;
 * &amp;lt;/complexType&amp;gt;
 * &lt;/pre&gt;* 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "OrderRequest", propOrder = {
    "accountId",
    "quantity"
})
public class OrderRequest {

    protected String accountId;
    protected Integer quantity;

    /**
     * Gets the value of the accountId property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getAccountId() {
        return accountId;
    }

    /**
     * Sets the value of the accountId property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setAccountId(String value) {
        this.accountId = value;
    }

    /**
     * Gets the value of the quantity property.
     * 
     * @return
     *     possible object is
     *     {@link Integer }
     *     
     */
    public Integer getQuantity() {
        return quantity;
    }

    /**
     * Sets the value of the quantity property.
     * 
     * @param value
     *     allowed object is
     *     {@link Integer }
     *     
     */
    public void setQuantity(Integer value) {
        this.quantity = value;
    }

}

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;OrderResponse.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.3 in JDK 1.6 
// See &lt;a href="http://java.sun.com/xml/jaxb"&gt;http://java.sun.com/xml/jaxb&lt;/a&gt; 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2012.02.07 at 05:07:31 PM EST 
//


package com.myapp.data.order;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;


/**
 * Java class for OrderResponse complex type.
 * 
 * 
The following schema fragment specifies the expected content contained within this class.
 * 
 * 
&lt;pre&gt;* &amp;lt;complexType name="OrderResponse"&amp;gt;
 *   &amp;lt;complexContent&amp;gt;
 *     &amp;lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&amp;gt;
 *       &amp;lt;sequence&amp;gt;
 *         &amp;lt;element name="orderId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&amp;gt;
 *         &amp;lt;element name="responseCode" type="{}responseCode" minOccurs="0"/&amp;gt;
 *         &amp;lt;element name="accountId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&amp;gt;
 *       &amp;lt;/sequence&amp;gt;
 *     &amp;lt;/restriction&amp;gt;
 *   &amp;lt;/complexContent&amp;gt;
 * &amp;lt;/complexType&amp;gt;
 * &lt;/pre&gt;* 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "OrderResponse", propOrder = {
    "orderId",
    "responseCode",
    "accountId"
})
public class OrderResponse {

    protected String orderId;
    protected ResponseCode responseCode;
    protected String accountId;

    /**
     * Gets the value of the orderId property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getOrderId() {
        return orderId;
    }

    /**
     * Sets the value of the orderId property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setOrderId(String value) {
        this.orderId = value;
    }

    /**
     * Gets the value of the responseCode property.
     * 
     * @return
     *     possible object is
     *     {@link ResponseCode }
     *     
     */
    public ResponseCode getResponseCode() {
        return responseCode;
    }

    /**
     * Sets the value of the responseCode property.
     * 
     * @param value
     *     allowed object is
     *     {@link ResponseCode }
     *     
     */
    public void setResponseCode(ResponseCode value) {
        this.responseCode = value;
    }

    /**
     * Gets the value of the accountId property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getAccountId() {
        return accountId;
    }

    /**
     * Sets the value of the accountId property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setAccountId(String value) {
        this.accountId = value;
    }

}


&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;ResponseCode.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.3 in JDK 1.6 
// See &lt;a href="http://java.sun.com/xml/jaxb"&gt;http://java.sun.com/xml/jaxb&lt;/a&gt; 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2012.02.07 at 05:07:31 PM EST 
//


package com.myapp.data.order;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;


/**
 * Java class for responseCode.
 * 
 * 
The following schema fragment specifies the expected content contained within this class.
 * 
* 
&lt;pre&gt;* &amp;lt;simpleType name="responseCode"&amp;gt;
 *   &amp;lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&amp;gt;
 *     &amp;lt;enumeration value="SUCCESS"/&amp;gt;
 *     &amp;lt;enumeration value="FAILED"/&amp;gt;
 *     &amp;lt;enumeration value="REJECTED"/&amp;gt;
 *     &amp;lt;enumeration value="UNKNOWN"/&amp;gt;
 *   &amp;lt;/restriction&amp;gt;
 * &amp;lt;/simpleType&amp;gt;
 * &lt;/pre&gt;* 
 */
@XmlType(name = "responseCode")
@XmlEnum
public enum ResponseCode {

    SUCCESS,
    FAILED,
    REJECTED,
    UNKNOWN;

    public String value() {
        return name();
    }

    public static ResponseCode fromValue(String v) {
        return valueOf(v);
    }

}

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The &lt;b&gt;ObjectFactory.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.3 in JDK 1.6 
// See &lt;a href="http://java.sun.com/xml/jaxb"&gt;http://java.sun.com/xml/jaxb&lt;/a&gt; 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2012.02.07 at 05:07:31 PM EST 
//


package com.myapp.data.order;

import javax.xml.bind.annotation.XmlRegistry;


/**
 * This object contains factory methods for each 
 * Java content interface and Java element interface 
 * generated in the com.myapp.data.order package. 
 * An ObjectFactory allows you to programatically 
 * construct new instances of the Java representation 
 * for XML content. The Java representation of XML 
 * content can consist of schema derived interfaces 
 * and classes representing the binding of schema 
 * type definitions, element declarations and model 
 * groups.  Factory methods for each of these are 
 * provided in this class.
 * 
 */
@XmlRegistry
public class ObjectFactory {


    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.myapp.data.order
     * 
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link OrderResponse }
     * 
     */
    public OrderResponse createOrderResponse() {
        return new OrderResponse();
    }

    /**
     * Create an instance of {@link OrderRequest }
     * 
     */
    public OrderRequest createOrderRequest() {
        return new OrderRequest();
    }

}

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Define the Web service interface &lt;b&gt;ExecutionWebService.java&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.webservice.orderexecutionservices;


import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import  com.myapp.data.order.*;

@Path("execution/1.0")
public interface ExecutionWebService {


    // -------------------------
    // Create Order
    // -------------------------
     
    @POST
    @Path("/order/create")
    @Consumes("application/xml") 
    @Produces("text/xml")
    OrderResponse createOrder(OrderRequest orderRequest);
    
    // -------------------------
    // Amend Order
    // -------------------------
    
    @POST
    @Path("/order/amend")
    @Consumes("application/xml")
    @Produces("text/xml")
    OrderResponse amendOrder(OrderRequest orderRequest);
    
    //--------------------------
    // Cancel Order
    //--------------------------
    
    @POST
    @Path("/order/cancel")
    @Consumes("application/xml")
    @Produces("text/xml")
    OrderResponse cancelOrder(OrderRequest orderRequest);

}


&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Define the Web service implementation class &lt;b&gt;ExecutionWebServiceImpl.java&lt;/b&gt;. This class makes use of the back-end service class OrderService.java to talk to to the DAO layer, which is not shown here.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.webservice.orderexecutionservices.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;


import com.myapp.data.order.OrderRequest;
import com.myapp.data.order.OrderResponse;

public class ExecutionWebServiceImpl implements ExecutionWebService {

    private OrderService orderService;

    public ExecutionWebServiceImpl() {
    }

    public ExecutionWebServiceImpl(OrderService orderService) {
        this.setOrderService(orderService);
    }

    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    public OrderService getOrderService() {
        return orderService;
    }

    @Override
    public OrderResponse createOrder(OrderRequest orderRequest) {
        OrderResponse response = null;
        try {
      //call to back end service 
            response = getOrderService().createOrder(orderRequest);
        } catch (Exceprion e) {
            throw new WebApplicationException(e);
        }
  
        return response;
    }

    @Override
    public OrderResponse amendOrder(OrderRequest orderRequest) {
       OrderResponse response = null;
        try {
            response = getOrderService().amendOrder(orderRequest);
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } 

        return response;
    }

    @Override
    public OrderResponse cancelOrder(OrderRequest orderRequest) {

        OrderResponse response = null;

        try {
            response = getOrderService().cancelOrder(orderRequest, null);
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } 

        return response;
    }
}

&lt;/pre&gt;&lt;br /&gt;
Now, wire up the above classes using Spring and CXF configuration files.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The &lt;b&gt;webservices-config.xml&lt;/b&gt; file.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:cxf="http://cxf.apache.org/core" 
 xmlns:jaxrs="http://cxf.apache.org/jaxrs" 
 xmlns:jaxws="http://cxf.apache.org/jaxws"
 xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://cxf.apache.org/jaxws 
    http://cxf.apache.org/schemas/jaxws.xsd
    http://cxf.apache.org/jaxrs 
    http://cxf.apache.org/schemas/jaxrs.xsd"&amp;gt;

 &amp;lt;import resource="classpath:META-INF/cxf/cxf.xml" /&amp;gt;
 &amp;lt;import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml" /&amp;gt;
 &amp;lt;import resource="classpath:META-INF/cxf/cxf-servlet.xml" /&amp;gt;
 &amp;lt;import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" /&amp;gt;
 &amp;lt;import resource="classpath:META-INF/cxf/cxf-extension-http.xml" /&amp;gt;

 
    &amp;lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --&amp;gt;
    &amp;lt;!-- Configure Execution Web Services Beans --&amp;gt;
    &amp;lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --&amp;gt;
 &amp;lt;bean id="executionWebService" class="com.myapp.webservice.orderexecutionservices.impl.ExecutionWebServiceImpl"&amp;gt;
  &amp;lt;constructor-arg ref="orderService" /&amp;gt;
 &amp;lt;/bean&amp;gt;
 
 &amp;lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --&amp;gt;
 &amp;lt;!-- CONFIGURE ENDPOINTS            --&amp;gt;
 &amp;lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --&amp;gt;
 &amp;lt;jaxrs:server id="executionservices" address="/executionservices/"&amp;gt;
  &amp;lt;jaxrs:inInterceptors&amp;gt;
   &amp;lt;ref bean="myAppInInterceptor" /&amp;gt;
  &amp;lt;/jaxrs:inInterceptors&amp;gt;
  &amp;lt;jaxrs:outInterceptors&amp;gt;
   &amp;lt;ref bean="myAppOutInterceptor" /&amp;gt;
  &amp;lt;/jaxrs:outInterceptors&amp;gt;
  &amp;lt;jaxrs:providers&amp;gt;
   &amp;lt;ref bean="exceptionMapperInterceptor" /&amp;gt;
  &amp;lt;/jaxrs:providers&amp;gt;
  &amp;lt;jaxrs:serviceBeans&amp;gt;
   &amp;lt;ref bean="executionWebService" /&amp;gt;
  &amp;lt;/jaxrs:serviceBeans&amp;gt;
 &amp;lt;/jaxrs:server&amp;gt;
    

 &amp;lt;!-- define orderService, interceptors etc. left out for brevity --&amp;gt;
 &amp;lt;!-- This can be defined in other Spring context files as well--&amp;gt;
 
&amp;lt;/beans&amp;gt;


&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The &lt;b&gt;cxf.xml &lt;/b&gt;file.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sec="http://cxf.apache.org/configuration/security"
 xmlns:http="http://cxf.apache.org/transports/http/configuration"
 xsi:schemaLocation="
          http://cxf.apache.org/configuration/security
          http://cxf.apache.org/schemas/configuration/security.xsd
          http://cxf.apache.org/transports/http/configuration
          http://cxf.apache.org/schemas/configuration/http-conf.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd"&amp;gt;

 &amp;lt;http:conduit name="*.http-conduit"&amp;gt;
  &amp;lt;http:tlsClientParameters secureSocketProtocol="SSL" disableCNCheck="true"/&amp;gt;
  &amp;lt;http:client AllowChunking="false" ReceiveTimeout="60000"/&amp;gt;
 &amp;lt;/http:conduit&amp;gt;
&amp;lt;/beans&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Finally, register the CXF servlet and bootstrap the above config files via &lt;b&gt;web.xml &lt;/b&gt;file. The web.xml file snippet is shown below.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 id="services" version="2.5"&amp;gt;
 &amp;lt;display-name&amp;gt;webservices&amp;lt;/display-name&amp;gt;

 &amp;lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ --&amp;gt;
 &amp;lt;!-- CONFIGURE SPRING CONTAINER --&amp;gt;
 &amp;lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ --&amp;gt;

 &amp;lt;context-param&amp;gt;
  &amp;lt;param-name&amp;gt;contextConfigLocation&amp;lt;/param-name&amp;gt;
  &amp;lt;param-value&amp;gt;
   classpath*:transactionContext.xml
   classpath*:daoContext.xml
           
   /WEB-INF/webservice-config.xml
   classpath*:/cxf.xml
   
  &amp;lt;/param-value&amp;gt;
 &amp;lt;/context-param&amp;gt;
 &amp;lt;listener&amp;gt;
  &amp;lt;listener-class&amp;gt;org.springframework.web.context.ContextLoaderListener&amp;lt;/listener-class&amp;gt;
 &amp;lt;/listener&amp;gt;

 &amp;lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ --&amp;gt;
 &amp;lt;!-- CONFIGURE CXF SERVLET      --&amp;gt;
 &amp;lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ --&amp;gt;
 &amp;lt;servlet&amp;gt;
  &amp;lt;servlet-name&amp;gt;CXFServlet&amp;lt;/servlet-name&amp;gt;
  &amp;lt;servlet-class&amp;gt;org.apache.cxf.transport.servlet.CXFServlet&amp;lt;/servlet-class&amp;gt;
  &amp;lt;load-on-startup&amp;gt;1&amp;lt;/load-on-startup&amp;gt;
 &amp;lt;/servlet&amp;gt;
 &amp;lt;servlet-mapping&amp;gt;
  &amp;lt;servlet-name&amp;gt;CXFServlet&amp;lt;/servlet-name&amp;gt;
  &amp;lt;url-pattern&amp;gt;/*&amp;lt;/url-pattern&amp;gt;
 &amp;lt;/servlet-mapping&amp;gt;

 &amp;lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ --&amp;gt;
 &amp;lt;!-- CONFIGURE JNDI RESOURCES   --&amp;gt;
 &amp;lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ --&amp;gt;
 &amp;lt;resource-ref&amp;gt;
  &amp;lt;description&amp;gt;My App Data Source&amp;lt;/description&amp;gt;
  &amp;lt;res-ref-name&amp;gt;jdbc/dataSource/MyDB&amp;lt;/res-ref-name&amp;gt;
  &amp;lt;res-type&amp;gt;javax.sql.DataSource&amp;lt;/res-type&amp;gt;
  &amp;lt;res-auth&amp;gt;Container&amp;lt;/res-auth&amp;gt;
 &amp;lt;/resource-ref&amp;gt;
 
&amp;lt;/web-app&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
Now, the sample client that consumes the Web service.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note that the interface classes like &lt;b&gt;ExecutionWebService&lt;/b&gt;, &lt;b&gt;OrederRequest&lt;/b&gt;, &lt;b&gt;OrderResponse&lt;/b&gt;, etc  will be  required by both the client (i.e. the Web service consumer) and the service implementation classes like &lt;b&gt;ExecutionWebServiceImpl &lt;/b&gt;(i.e. service provider). Hence, the interface classes need to be packaged as separate jar file to be used by both the client and the service implementation.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.webservice.client;

import org.apache.cxf.jaxrs.client.Client;
import org.apache.cxf.jaxrs.client.JAXRSClientFactory;

//...other imports

public class ExecutionWebServiceClient {

    private static final String EXECUTION_SERVICES_CONTEXT_ROOT = "executionservices";
    
   
    public void consumeRestWebService( ) Throws Exception {
        ExecutionWebService serviceClient = JAXRSClientFactory.create("http://localhost:8080" + EXECUTION_SERVICES_CONTEXT_ROOT, ExecutionWebService.class);
        OrderRequest request = constructOrderReqObj(); // not shown
        OrderResponse response = serviceClient.createOrder(request); 
        //... do something with the response.  
    }   
}

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The URLs that we be used will be like&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;http://localhost:8080/executionservices/execution/1.0/order/create
http://localhost:8080/executionservices/execution/1.0/order/amend
http://localhost:8080/executionservices/execution/1.0/order/cancel

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
That's all to it. You can also test your Web service using the "poster" plugin for Firefox.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The request payload will be something like:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;OrderRequest&amp;gt;
  &amp;lt;orderId&amp;gt;orderId&amp;lt;/orderId&amp;gt;
  &amp;lt;responseCode&amp;gt;responseCode&amp;lt;/responseCode&amp;gt;
  &amp;lt;accountId&amp;gt;accountId&amp;lt;/accountId&amp;gt;
&amp;lt;/OrderRequest&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The response payload will be something like&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;OrderResponse&amp;gt;
  &amp;lt;orderId&amp;gt;orderId&amp;lt;/orderId&amp;gt;
  &amp;lt;responseCode&amp;gt;responseCode&amp;lt;/responseCode&amp;gt;
  &amp;lt;accountId&amp;gt;accountId&amp;lt;/accountId&amp;gt;
&amp;lt;/OrderResponse&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Note&lt;/b&gt;: You could generate the payload from the XSD file within eclipse IDE by selecting the schema file and then right clicking to click on Generate --&amp;gt; XML. Make sure you check optional elements to be included. It will also require a root element, henc you need to wrap you r schema with something like &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;xs:element name="OrderRequest" &amp;gt;
   
   .......
 
&amp;lt;/xs:element&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
to generate the request payload and &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;xs:element name="OrderResponse" &amp;gt;
   
   .......
 
&amp;lt;/xs:element&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
to generate the response payload within eclipse IDE.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div style="color: #274e13;"&gt;&lt;b&gt;&lt;span style="font-size: large;"&gt;Other relevant links on Web Services&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;&lt;br /&gt;
&lt;a href="http://java-success.blogspot.com.au/2012/02/java-web-services-interview-questions.html"&gt;Web Services Interview Questions and Answers - Overview &lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-5183680927792475996?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/AIAOFMt8D5MYTqYUs_U5VDD3iGM/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/AIAOFMt8D5MYTqYUs_U5VDD3iGM/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/AIAOFMt8D5MYTqYUs_U5VDD3iGM/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/AIAOFMt8D5MYTqYUs_U5VDD3iGM/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/5gvh-pjGYg8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/5183680927792475996/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=5183680927792475996" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/5183680927792475996?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/5183680927792475996?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/5gvh-pjGYg8/web-services-interview-questions-and.html" title="Web Services Interview Questions and Answers - RESTful Web Service Overview" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2012/02/web-services-interview-questions-and.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEADSHg8fyp7ImA9WhRaEko.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-7502934090775494730</id><published>2012-02-09T17:31:00.000-08:00</published><updated>2012-02-14T18:26:19.677-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-02-14T18:26:19.677-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Web Service Interview Answers" /><category scheme="http://www.blogger.com/atom/ns#" term="Java Web Service Interview Answers" /><category scheme="http://www.blogger.com/atom/ns#" term="Web Service Interview Questions" /><category scheme="http://www.blogger.com/atom/ns#" term="Java Web Service Interview Questions" /><title>Java Web Services Interview Questions and Answers: Overview</title><content type="html">&lt;b&gt;Q.&lt;/b&gt; What are the different application integration styles?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;There are a number of different integration styles like&lt;br /&gt;
&lt;br /&gt;
1. Shared database&lt;br /&gt;
2. batch file transfer&lt;br /&gt;
3. Invoking remote procedures (RPC)&lt;br /&gt;
4. Exchanging asynchronous messages over a message oriented middle-ware (MOM).&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-PzRrLNGPU9U/TzSyk9vzpYI/AAAAAAAAASk/wsDCrNTg9FM/s1600/integration-styles.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="640" src="http://1.bp.blogspot.com/-PzRrLNGPU9U/TzSyk9vzpYI/AAAAAAAAASk/wsDCrNTg9FM/s640/integration-styles.JPG" width="596" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. &lt;/b&gt;What are the different styles of Web Services used for application integration? &lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; &lt;b&gt;SOAP WS&lt;/b&gt; and &lt;b&gt;RESTful &lt;/b&gt;Web Service&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; What are the differences between both SOAP WS and RESTful WS?&amp;nbsp; &lt;br /&gt;
&lt;b&gt;A.&amp;nbsp; &lt;/b&gt;&lt;b&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style. &lt;/li&gt;
&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S),&amp;nbsp; Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.&lt;/li&gt;
&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations.&lt;/li&gt;
&lt;/ul&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; GET - represent()&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; POST - acceptRepresention()&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; PUT - storeRepresention()&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; DELETE - removeRepresention() &lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better. &lt;/li&gt;
&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;SOAP WS wupports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not. &lt;/li&gt;
&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;The SOAP has comprehensive support for both ACID based&amp;nbsp; transaction management&amp;nbsp; for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it&amp;nbsp; is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How would you decide what style of Web Service to use? SOAP WS or REST?&lt;br /&gt;
&lt;b&gt;A&lt;/b&gt;. In general, a REST based Web service is preferred due to its simplicity, performance, scalability, and support for multiple data formats. SOAP is favored where service requires comprehensive support for security and transactional reliability.&lt;br /&gt;
&lt;br /&gt;
The answer really depends on the functional and non-functional requirements. Asking the questions listed below will help you choose.&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;b&gt;Does the service expose data or business logic? &lt;/b&gt;(REST is a better choice for exposing data, SOAP WS might be a better choice for logic).Do the consumers and the service providers require a formal contract? (SOAP has a formal contract via WSDL)&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Do we need to support multiple data formats? &lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Do we need to make AJAX calls? &lt;/b&gt;(REST can use the XMLHttpRequest)&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Is the call synchronous or&amp;nbsp; asynchronous?&lt;/b&gt; &lt;/li&gt;
&lt;li&gt;&lt;b&gt;Is the call stateful or stateless?&lt;/b&gt; (REST is suited for statless CRUD operations)&lt;/li&gt;
&lt;li&gt;&lt;b&gt;What level of security is required?&lt;/b&gt; (SOAP WS has better support for security)&lt;/li&gt;
&lt;li&gt;&lt;b&gt;What level of transaction support is required? &lt;/b&gt;(SOAP WS has better support for transaction management)&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Do we have limited band width?&lt;/b&gt; (SOAP is more verbose)&lt;/li&gt;
&lt;li&gt;&lt;b&gt;What’s best for the developers who will build clients for the service? &lt;/b&gt;(REST is easier to implement, test, and maintain)&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. &lt;/b&gt;What tools do you use to test your Web Services?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; &lt;b&gt;SoapUI&lt;/b&gt; tool for SOAP WS and the Firefox "&lt;b&gt;poster&lt;/b&gt;" plugin for RESTFul services.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; What is the difference between SOA and a Web service? &lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;SOA is &lt;/b&gt;a software design principle and an architectural pattern for implementing loosely coupled, reusable and coarse grained services. You can implement SOA using any protocols such as HTTP, HTTPS, JMS, SMTP, RMI, IIOP (i.e. EJB uses IIOP), RPC etc. Messages can be in XML or Data Transfer Objects (DTOs).&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Web service is&lt;/b&gt; an implementation technology and one of the ways to implement SOA. You can build SOA based applications without using Web services – for example by using other traditional technologies like Java RMI, EJB, JMS based messaging, etc. But what Web services offer is the standards based&amp;nbsp; and platform-independent service via HTTP, XML, SOAP, WSDL and UDDI, thus allowing interoperability between heterogeneous technologies such as J2EE and .NET. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; Web services when you can use traditional style middle-ware such as RPC, CORBA, RMI and DCOM?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The&lt;b&gt; traditional middle-wares&lt;/b&gt; tightly couple connections to the applications and it can break if you make any modification to your application. Tightly coupled applications are hard to maintain and less reusable. Generally do not support heterogeneity. Do not work across Internet. Can be more expensive and hard to use. &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Web Services&lt;/b&gt; support loosely coupled connections. The interface of the Web service provides a layer of abstraction between the client and the server. The loosely coupled applications reduce the cost of maintenance and increases re-usability. Web Services present a new form of middle-ware based on XML and Web. Web services are language and platform independent. You can develop a Web service using any language and deploy it on to any platform, from small device to the largest supercomputer. Web service uses language neutral protocols such as HTTP and communicates between disparate applications by passing XML messages to each other via a Web API. Do work across internet, less expensive and easier to use.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. &lt;/b&gt;What are the different approaches to developing a SOAP based Web service?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;2 approaches.&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;The &lt;b&gt;contract-first&lt;/b&gt; approach, where you define the contract first with XSD and WSDL and the generate the Java classes from the contract. &lt;/li&gt;
&lt;li&gt;The &lt;b&gt;contract-last &lt;/b&gt;approach where you&amp;nbsp; define the Java classes first and then generate the contract, which is the&amp;nbsp; WSDL file from the Java classes.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;b&gt;Note:&lt;/b&gt; The WSDL describes all operations that the service provides, locations of the endpoints (i.e.e where the services can be invoked), and simple and complex elements that can be passed in requests and responses.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; What are the pros and cons of each approach, and which approach would you prefer?&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Contract-first Web service&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;PROS:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Clients are decoupled from the server, hence the implementation logic can be revised on the server without affecting the clients.&lt;/li&gt;
&lt;li&gt;Developers can work simultaneously on client and server side based on the contract both agreed on.&lt;/li&gt;
&lt;li&gt;You have full control over how the request and response messages are constructed -- for example, should "status" go as an element or as an attribute? The contract clearly defines it. You can change OXM (i.e. Object to XML Mapping) libraries without having to worry if the "status" would be generated as "attribute" instead of an element. Potentially, even Web service frameworks and tool kits can be changed as well from say Apache Axis to Apache CXF, etc &lt;/li&gt;
&lt;/ul&gt;&amp;nbsp; &lt;br /&gt;
&lt;b&gt;CONS:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;More upfront work is involved in setting up the XSDs and WSDLs. There are tools like XML Spy, Oxygen XML, etc to make things easier. The object models need to be written as well.&lt;br /&gt;
&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Developers need to learn XSDs and WSDLs in addition to just knowing Java.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&lt;b&gt;Contract-last Web service&lt;/b&gt;&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&lt;b&gt;PROS:&lt;/b&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Developers don't have to learn anything related to XSDs, WSDLs, and SOAP. The services are created quickly by exposing the existing service logic with frameworks/tool sets. For example, via IDE based wizards, etc.&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;The learning curve and development time can be smaller compared to the Contract-first Web service. &lt;/li&gt;
&lt;/ul&gt;&amp;nbsp; &lt;br /&gt;
&lt;b&gt;CONS: &lt;/b&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&amp;nbsp;The development time can be shorter to initially develop it, but what about the on going maintenance and extension time if the contract changes or new elements need to be added? In this approach, since the clients and servers are more tightly coupled, the future changes may break the client contract and affect all clients or require the services to be properly versioned and managed.&lt;/li&gt;
&lt;li&gt;&amp;nbsp;In this approach, The XML payloads cannot be controlled. This means changing your OXM libraries could cause something that used to be an element to become an attribute with the change of the OXM.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;So, which approach will you choose?&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The best practice is to use "&lt;b&gt;contract-first&lt;/b&gt;", and here is the link that explains this much better with examples --&amp;gt;&amp;nbsp; &lt;a href="http://static.springsource.org/spring-ws/site/reference/pdf/spring-ws-reference.pdf" target="_blank"&gt;contract-first versus contract-last web services&lt;/a&gt; In a nutshell, the contract-last is more fragile than the "contract-first".&amp;nbsp; You will have to decide what is most appropriate based on your requirements, tool sets you use, etc.&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Note&lt;/b&gt;: More Java Web Services interview questions and answers including WSDL, SOAP, UDDI, JAXR, SAAJ, etc are covered in Java/J2EE Job Interview Companion with diagrams.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div style="color: #134f5c;"&gt;&lt;b&gt;&lt;span style="font-size: large;"&gt;More Web services Interview Questions and Answers&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;&lt;br /&gt;
&lt;a href="http://java-success.blogspot.com.au/2012/02/web-services-interview-questions-and.html"&gt;Java Web Services Interview Questions and Answers: RESTful Web services&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-7502934090775494730?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/LeeFq8k2mtSiybRdx354uw01v0M/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/LeeFq8k2mtSiybRdx354uw01v0M/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/LeeFq8k2mtSiybRdx354uw01v0M/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/LeeFq8k2mtSiybRdx354uw01v0M/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/kJwBXQU_U2o" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/7502934090775494730/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=7502934090775494730" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/7502934090775494730?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/7502934090775494730?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/kJwBXQU_U2o/java-web-services-interview-questions.html" title="Java Web Services Interview Questions and Answers: Overview" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://1.bp.blogspot.com/-PzRrLNGPU9U/TzSyk9vzpYI/AAAAAAAAASk/wsDCrNTg9FM/s72-c/integration-styles.JPG" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2012/02/java-web-services-interview-questions.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CU4GRX8-fCp7ImA9WhRbF00.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-786295901856460825</id><published>2012-02-08T04:25:00.000-08:00</published><updated>2012-02-08T04:25:24.154-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-02-08T04:25:24.154-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Hibernate interview answers" /><category scheme="http://www.blogger.com/atom/ns#" term="Spring Interview Questions and Answers" /><category scheme="http://www.blogger.com/atom/ns#" term="HIbernate Interview Questions" /><category scheme="http://www.blogger.com/atom/ns#" term="Spring interview questions" /><category scheme="http://www.blogger.com/atom/ns#" term="Spring interview answers" /><category scheme="http://www.blogger.com/atom/ns#" term="Hibernate interview questions and answers" /><title>Hibernate Interview Questions and Answers: integration testing the DAO layer</title><content type="html">Before this, please refer to&amp;nbsp;&lt;a href="http://java-success.blogspot.com.au/2012/01/hibernate-interview-q-with-annotations.html" target="_blank"&gt;Hibernate Interview Questions and Answers: with annotations and Spring framework&lt;/a&gt; , as the examples below are extension of this blog. &lt;b&gt;&lt;br /&gt;
&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. &lt;/b&gt;How would you go about integration testing your DAO (i.e. Data Access Objects) layer or your Hibernate Repository classes?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; It is a bit tricky to write integration tests because any changes to the underlying data can make your tests to fail. For example, addition of new records, modification to existing data , etc. The key is to keep the data as static as possible. There are two possible strategies. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;1.&lt;/b&gt; Use a separate in memory database like &lt;b&gt;HSQL &lt;/b&gt;(i.e. Hyper Structured Query Language) Database. The data can be stored in flat text files -- say in pipe delimited format and loaded into the in memory database during test set up phase, and deleted during the test tear down phase.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;2.&lt;/b&gt; The second alternative is to use a framework like DBUnit to extract the relevant data from a given database and convert it into XML based data sets that can be inserted into your test database during the test setUp phase and deleted in the test tear-down phase. The &lt;b&gt;DBUnit &lt;/b&gt;takes care of the data extraction and data load.&lt;br /&gt;
&lt;br /&gt;
Both the above approaches maintain static data in either xml or text based flat files and load the data during the test setup.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. &lt;/b&gt;How would you go about using an in memory database like HSQL DB?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;It involves the following steps.&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Define the data in flat files. Say in pipe delimited format.&lt;/li&gt;
&lt;li&gt;Write the parser classes to read the data and convert them into SQL insert statements to be loaded into the HSQL DB. This is known as ETL (i.e. Extract Transform Load) operation. &lt;/li&gt;
&lt;li&gt;Override the default hibernate datasource proprties with the HSQL DB related configuration.&lt;/li&gt;
&lt;li&gt;Wire up the datasource override file via override-daoContext.xml, which uses the HSQL DB, and overrides the hibernate proprties from the file daoContext.xml.&lt;/li&gt;
&lt;li&gt;Write a mock HSQL DB JNDI bootstrap class and wire it up using a Spring context file (e.g. hsqlBootstrapContext.xml).&lt;/li&gt;
&lt;li&gt;Write a database populator class that makes use of a number of parser classes to populate the database. Also, wire this up via a Spring context file (e.g. databasePopulatorContext.xml)&lt;/li&gt;
&lt;li&gt;Finally, the test class that bootstraps all the relevant classes via the Spring context files using dependency injection.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
Define the data in a flat file say&lt;b&gt; employeeSearch.txt&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;#employee_id, emp_code, manager_code, type, base_salary
A342|XSMITH|A456|IM|Permanent|43,500.00
A342|YSMITH|A678|IM|Contract|57,700.00 

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Define the parser that loads the data by reading from the above flat file. For e.g.&lt;b&gt; EmployeeParser.java&lt;/b&gt;. This class can be further improved by moving out the methods that will be shared by other parsers to a parent class or a helper class.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.database;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

public class EmployeeParser {

 private static final String DROP_SQL = "drop table tbl_employee";
    private static final String CREATE_SQL =
            "create table tbl_employee(employee_id varchar(12), emp_code varchar(12), " + 
            "manager_code  varchar(12), type  varchar(12), base_salary decimal";


    private static final String INSERT_SQL =
            "insert into tbl_employee (employee_id, emp_code, manager_code, type, base_salary) values (";

   
    public void parseEmployee(Session session) throws ParserException, IOException {
        createDatabaseTable(session);
        BufferedReader file = findFile(getFileName());
        String[] data = readLine(file);
        while (data != null) {
            Query query =
                    session.createSQLQuery(INSERT_SQL + "'" + data[0] + "','" + data[1] + "','"
                            + data[2] + "'," + data[3] +  "','" + data[4] + ")");
            query.executeUpdate();
            data = readLine(file); // read next line from the file
        }
    }
    
    
    protected String[] readLine(BufferedReader file) throws IOException {
     String[] data = null;
        String line = file.readLine();
        while (line != null &amp;amp;&amp;amp; line.startsWith("#")) {
            line = file.readLine();
        }
        if (line != null) {
         data =  line.split("\\|"); //split by "|" 
        }
        return data;
    }


    private void createDatabaseTable(Session session) {
        Query query = session.createSQLQuery(DROP_SQL);
        try {
            query.executeUpdate();
        } catch (HibernateException e) {
        }
        query =  session.createSQLQuery(CREATE_SQL);
        query.executeUpdate();
    }
    
    protected BufferedReader findFile(String fileName) {
        final InputStreamReader file =
                new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName));
        BufferedReader stream = new BufferedReader(file);
        return stream;
    }

  

    public String getFileName() {
        return "employeeSearch.txt";
    }

}
 
&lt;/pre&gt;&lt;br /&gt;
Define an override spring context file to override the actual datasource properies. For example, the actual database could be Sybase or Oracle. The &lt;b&gt;override-daoContext.xml &lt;/b&gt;is shown below.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-2.5.xsd"
 default-autowire="byName"&amp;gt;

    &amp;lt;bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"&amp;gt;
        &amp;lt;property name="properties"&amp;gt;
            &amp;lt;props&amp;gt;
                &amp;lt;prop key="hibernate.dialect"&amp;gt;org.hibernate.dialect.HSQLDialect&amp;lt;/prop&amp;gt;
                &amp;lt;prop key="hibernate.generate_statistics"&amp;gt;true&amp;lt;/prop&amp;gt;
                &amp;lt;prop key="hibernate.hbm2ddl.auto"&amp;gt;create-drop&amp;lt;/prop&amp;gt;
                &amp;lt;prop key="hibernate.jdbc.batch_size"&amp;gt;1000&amp;lt;/prop&amp;gt;
                &amp;lt;prop key="hibernate.show_sql"&amp;gt;true&amp;lt;/prop&amp;gt;
                &amp;lt;prop key="hibernate.use_sql_comments"&amp;gt;true&amp;lt;/prop&amp;gt;
                &amp;lt;prop key="hibernate.cache.use_query_cache"&amp;gt;false&amp;lt;/prop&amp;gt;
                &amp;lt;prop key="hibernate.cache.use_second_level_cache"&amp;gt;false&amp;lt;/prop&amp;gt;
                &amp;lt;prop key="hibernate.query.factory_class"&amp;gt;org.hibernate.hql.classic.ClassicQueryTranslatorFactory&amp;lt;/prop&amp;gt;
            &amp;lt;/props&amp;gt;
        &amp;lt;/property&amp;gt;
        &amp;lt;property name="location"&amp;gt;
            &amp;lt;value&amp;gt;classpath:/hibernate.properties&amp;lt;/value&amp;gt;
        &amp;lt;/property&amp;gt;
    &amp;lt;/bean&amp;gt;


&amp;lt;/beans&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Write a JNDI based bootstrapper class &lt;b&gt;HsqlDevBootstrapper.java&lt;/b&gt; that emulates JNDI boot strapping for your test classes. This is achieved via the Spring mock class SimpleNamingContextBuilder.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.test.db;
 
import javax.naming.NamingException;
 
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
 
/**
 * helper class to bootstrap the sybase database datasources
 */
public class HsqlDevBootstrapper  {
     
 public static final String JNDI_BINDING_DB = "java:comp/env/jdbc/dataSource/mydb";
    public static final String DRIVER_CLASS = "org.hsqldb.jdbcDriver";
 
 private SimpleNamingContextBuilder builder;  //Spring JNDI mock class
 
 /**
  * setup HSQL DB, and bind it to jndi tree
  */
 public void start() {
        try {
            builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
 
            DriverManagerDataSource ds = new DriverManagerDataSource();
            ds.setDriverClassName(DRIVER_CLASS);
            ds.setUrl("jdbc:hsqldb:mem:my_db"); //in memory HSQL DB URL
            ds.setUsername("user");
            ds.setPassword("pwd");
            builder.bind(JNDI_BINDING_DB, ds);
             
             
        } catch (NamingException e) {
            throw new BeanCreationException(e.getExplanation());
        }
    }
  
 public void stop() {
    builder.deactivate();
    builder.clear();
 }
 
}

&lt;/pre&gt;&lt;br /&gt;
Wire up the JNDI bootstrap class via Spring the config file hsqlBootstrapContext.xml.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-2.5.xsd"
 default-autowire="byName"&amp;gt;

 &amp;lt;bean id="hsqlBootstrapper" class="com.myapp.test.db.HsqlBootstrapper" init-method="start" destroy-method="stop"/&amp;gt;

&amp;lt;/beans&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Define a &lt;b&gt;DatabasePopulator.java&lt;/b&gt; class that populates all the relevant (i.e. associated) database tables incling tbl_employee.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.database;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.HibernateTemplate;


public class DatabasePopulator {

    private final HibernateTemplate daoTemplate;

   

    public DatabasePopulator(HibernateTemplate daoTemplate) throws Exception {
        this.daoTemplate = daoTemplate;
        try {
            createDB();
        } catch (Exception e) {
            throw e;
        }
    }

 /**
   * This is where all the loading happens
   */
    public void createDB() throws HibernateException, SQLException, IOException {
        Session session = daoTemplate.getSessionFactory().openSession();
  
  Transaction tran = session.beginTransaction();
  
  //make use of the parser to read the data from a file and load it (i.e. ETL operation - Extract, Transaform, and Load)
        EmployeeParser empParser = new EmployeeParser();
  empParser.parseEmployee(session);
        
  //load other relevant data
  
        session.flush();
        tran.commit();   
    }
 
}

&lt;/pre&gt;&lt;br /&gt;
Wire the DatabasePopulator via Spring config file &lt;b&gt;databasePopulatorContext.xml&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-2.5.xsd"
 default-autowire="byName"&amp;gt;

    &amp;lt;bean name="databasePopulator" class="com.myapp.database.DatabasePopulator"&amp;gt;
        &amp;lt;constructor-arg ref="daoTemplate" /&amp;gt;
    &amp;lt;/bean&amp;gt;
 
&amp;lt;/beans&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
Finally the test class. Some of the missing Spring context files and classes were defined in a different blog entry mentioned at the beginning of this blog. The context files need to be loaded in the right order.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.repository;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;



@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
  "classpath:hsqlBootstrapContext.xml",
  "classpath:transactionContext.xml",
  "classpath:daoContext.xml",
        "classpath:override-daoContext.xml",
        "classpath:databasePopulatorContext.xml"
})
@TestExecutionListeners(value = { 
  DependencyInjectionTestExecutionListener.class,
  SessionBindingHibernateListener.class
})

public class EmployeeRepositoryTest {

 @Resource
 EmployeeTableRepository  tableRepository;
    
    @Test
    public void testLoadEmployee() {
 
     Assert.assertTrue(tableRepository != null);
        Emplyee employee = null; 
        try {
            employee = tableRepository.loadEmployee("A342");
        } catch (RepositoryException e) {
            fail("Load employee threw an exception " + e);
        }
  
  assertTrue(employee != null);
        assertEquals(employee.getType(), "Permanent");
  //...more assertions
       
    }
 
 
 //....test other repository methods like saveEmployee, etc.
}


&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-786295901856460825?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/74KFo8Eyp7R1CXhtAEbzE-81u5U/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/74KFo8Eyp7R1CXhtAEbzE-81u5U/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/74KFo8Eyp7R1CXhtAEbzE-81u5U/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/74KFo8Eyp7R1CXhtAEbzE-81u5U/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/vNIQ5TsGUwA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/786295901856460825/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=786295901856460825" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/786295901856460825?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/786295901856460825?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/vNIQ5TsGUwA/hibernate-interview-questions-and.html" title="Hibernate Interview Questions and Answers: integration testing the DAO layer" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2012/02/hibernate-interview-questions-and.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DUEGR38yfSp7ImA9WhRbFU0.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-529392984664280841</id><published>2012-02-05T21:53:00.000-08:00</published><updated>2012-02-05T21:53:46.195-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-02-05T21:53:46.195-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="HIbernate Interview Questions" /><category scheme="http://www.blogger.com/atom/ns#" term="Spring interview questions" /><category scheme="http://www.blogger.com/atom/ns#" term="Spring interview answers" /><category scheme="http://www.blogger.com/atom/ns#" term="Hibernate interview questions and answers" /><title>Spring and Hibernate Interview Questions and Answers: AOP, interceptors, and deadlock retry</title><content type="html">Before this, please refer to &lt;a href="http://java-success.blogspot.com.au/2012/01/hibernate-interview-q-with-annotations.html" target="_blank"&gt;Hibernate Interview Questions and Answers: with annotations and Spring framework &lt;/a&gt;&amp;nbsp; , as the examples below are extension of this blog.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How would you go about implementing a dead lock retry service using Spring and hibernate?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Define an annotation to annotate the methods that needs deadlock retry service. E.g. DeadlockRetry.java&lt;/li&gt;
&lt;li&gt;Define the interceptor that gets wired up via AOP to perform the retry functionality by invoking the annotated method. E.g. DeadlockRetryMethodInterceptor&lt;/li&gt;
&lt;li&gt;Wire up the annotation and deadlock retry classes via Spring config. E.g. transactionContext.xml&lt;/li&gt;
&lt;li&gt;Finally, annotate the method that needs perform the retry service. E.g. EmployeeServiceImpl --&amp;gt; saveEmployee (....)&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Define a custom annotation class &lt;b&gt; DeadlockRetry&lt;/b&gt;.java.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.deadlock;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface DeadlockRetry {

    int maxTries() default 21;
    int tryIntervalMillis() default 100;
    
}

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Define the &lt;b&gt;DeadlockRetryMethodInterceptor &lt;/b&gt;for performing retries. The above annotation will be bound to the following implementation via Spring.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.deadlock;

import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.exception.LockAcquisitionException;
import org.springframework.dao.DeadlockLoserDataAccessException;


public class DeadlockRetryMethodInterceptor implements MethodInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(DeadlockRetryMethodInterceptor.class);
        
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Object obj = invocation.getThis();
        Method method = invocation.getMethod();
        Method targetMethod = obj.getClass().getMethod(method.getName(), method.getParameterTypes());
        DeadlockRetry dlRetryAnnotation = targetMethod.getAnnotation(DeadlockRetry.class);
        int maxTries = dlRetryAnnotation.maxTries();
        int tryIntervalMillis = dlRetryAnnotation.tryIntervalMillis();
        for (int i = 0; i &amp;lt; maxTries; i++) {
            try {
                LOGGER.info("Attempting to invoke " + invocation.getMethod().getName());
                Object result = invocation.proceed();    // retry
                LOGGER.info("Completed invocation of " + invocation.getMethod().getName());
                return result;
            } catch (Throwable e) {
                Throwable cause = e;
    
      //... put the logic to identify DeadlockLoserDataAccessException or LockAcquisitionException
      //...in the cause. If the execption is not due to deadlock, throw an exception 
    
            if (tryIntervalMillis &amp;gt; 0) {
              try {
                  Thread.sleep(tryIntervalMillis);
              } catch (InterruptedException ie) { 
                LOGGER.warn("Deadlock retry thread interrupted", ie);
              }
            }
    
        }
  
        //gets here only when all attempts have failed
        throw new RuntimeException
            ("DeadlockRetryMethodInterceptor failed to successfully execute target " 
                    + " due to deadlock in all retry attempts", 
              new DeadlockLoserDataAccessException("Created by DeadlockRetryMethodInterceptor", null));
    }    
}


&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Wire up the annotation and the interceptor via Spring config transactionContext.xml. Only the snippet is shown.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --&amp;gt;
    &amp;lt;!-- Deadlock Retry AOP             --&amp;gt;
    &amp;lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --&amp;gt;
    &amp;lt;bean id="deadlockRetryPointcut" class="org.springframework.aop.support.annotation.AnnotationMatchingPointcut"&amp;gt;
            &amp;lt;constructor-arg&amp;gt;&amp;lt;null/&amp;gt;&amp;lt;/constructor-arg&amp;gt;
            &amp;lt;constructor-arg value="com.myapp.deadlock.DeadlockRetry" /&amp;gt;
    &amp;lt;/bean&amp;gt;
 
    &amp;lt;bean id="deadlockRetryMethodInterceptor" lass="com.myapp.deadlock.DeadlockRetryMethodInterceptor" /&amp;gt;
 
    &amp;lt;bean id="deadlockRetryPointcutAdvisor"
        class="org.springframework.aop.support.DefaultPointcutAdvisor"&amp;gt;
            &amp;lt;constructor-arg ref="deadlockRetryPointcut" /&amp;gt;
            &amp;lt;constructor-arg ref="deadlockRetryMethodInterceptor" /&amp;gt;        
    &amp;lt;/bean&amp;gt;

 
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Finally, annotate the method that needs to be reried in the event of dead lock issues.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.service;


import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
//....other imports

public class EmployeeServiceImpl implements EmployeeService {
    
    private final EmployeeTableRepository employeeRepository;
    private PlatformTransactionManager transactionManager;
   
    public EmployeeServiceImpl(EmployeeTableRepository employeeRepository, PlatformTransactionManager transactionManager) {
        this.employeeRepository = employeeRepository;
        this.transactionManager = transactionManager;
    }


    @DeadlockRetry
    public Employee saveEmployee(Employeee employee) throws RepositoryException {
        TransactionStatus transactionStatus =
                transactionManager.getTransaction(new DefaultTransactionDefinition(
                        TransactionDefinition.PROPAGATION_REQUIRED));
        try {
            employee = this.employeeRepository.saveEmployee(employee);
        } catch (Exception e) {
            transactionManager.rollback(transactionStatus);
            throw new RepositoryException(e);
        } finally {
            if (!transactionStatus.isCompleted()) {
                transactionManager.commit(transactionStatus);
            }
        }
        return employee;
    }
 
 
 //....other methods omitted for brevity

}&amp;nbsp;&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The above example gives a real life example using a &lt;b&gt;custom annotation &lt;/b&gt;and &lt;b&gt;AOP &lt;/b&gt;(i.e. Aspect Oriented Programming).&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Note: &lt;/b&gt;Also refer to &lt;a href="http://java-success.blogspot.com.au/2011/11/spring-interview-questions-and-answers_30.html" target="_blank"&gt;Spring Interview Questions and Answers for explanation on interceptors.&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-529392984664280841?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/LxPRhhM96eSJdtTHPFH9i06Rmjs/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/LxPRhhM96eSJdtTHPFH9i06Rmjs/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/LxPRhhM96eSJdtTHPFH9i06Rmjs/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/LxPRhhM96eSJdtTHPFH9i06Rmjs/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/RK4QTApL_LA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/529392984664280841/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=529392984664280841" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/529392984664280841?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/529392984664280841?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/RK4QTApL_LA/spring-and-hibernate-interview.html" title="Spring and Hibernate Interview Questions and Answers: AOP, interceptors, and deadlock retry" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://java-success.blogspot.com/2012/02/spring-and-hibernate-interview.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DE4GQH0-fCp7ImA9WhRbEUk.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-7062161203125898355</id><published>2012-01-31T19:43:00.000-08:00</published><updated>2012-02-01T17:42:01.354-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-02-01T17:42:01.354-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Hibernate interview answers" /><category scheme="http://www.blogger.com/atom/ns#" term="HIbernate Interview Questions" /><category scheme="http://www.blogger.com/atom/ns#" term="Hibernate interview questions and answers" /><title>Hibernate Interview Questions and Answers: with annotations and Spring framework</title><content type="html">&lt;b&gt;Q.&lt;/b&gt; What are the general steps involved in creating Hibernate related class? &lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; The general steps involved in creating Hibernate related classes involve the following steps&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Define the domain (aka entity) objects like Employee, Address, etc to represent relevant tables in the underlying database with the appropriate annotations or using the *.hbm.xml mapping files.&lt;/li&gt;
&lt;li&gt;Define the &lt;i&gt;Repository&amp;nbsp; &lt;/i&gt;(aka DAO -- &lt;u&gt;D&lt;/u&gt;ata &lt;u&gt;A&lt;/u&gt;ccess &lt;u&gt;O&lt;/u&gt;bjects)&lt;i&gt; &lt;/i&gt;interfaces and implementations classes that use the domain objects and the hibernate session to perform data base CRUD (Create, Read, Update and Delete) operations the hibernate way.&lt;/li&gt;
&lt;li&gt;Define the service interfaces and the classes that make use of one or more repositories (aka DAOs) in a transactional context.A transaction manager will be used to coordinate transactions (i.e. commit or rollback) between&amp;nbsp; a number of repositories.&lt;/li&gt;
&lt;li&gt;Finally, use an IoC container like Spring framework to wire up the Hibernate classes like &lt;i&gt;SessionFactory&lt;/i&gt;, Session, transaction manager, etc and the user defined repositories, and the service classes. A number of interceptors can be wired up as well for deadlock retry, logging, auditing, etc using Spring.&lt;/li&gt;
&lt;/ul&gt;For more detail, refer to &lt;a href="http://java-success.blogspot.com.au/2011/11/spring-interview-questions-and-answers_30.html" target="_blank"&gt;Spring and Hibernate integration Interview questions and answers&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How would you define a hibernate domain object with table mappings, native named queries, and custom data conversion using annotations?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Firstly, define a parent domain object class for any common method implementations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.domain.model;

public class MyAppDomainObject {
    
 //for example
    protected boolean isPropertyEqual(Object comparee, Object compareToo) {
        if (comparee == null) {
            if (compareToo != null) {
                return false;
            }
        } else if (!comparee.equals(compareToo)) {
            return false;
        }
        return true;
    }

}

&lt;/pre&gt;&lt;br /&gt;
Now, extend the common DomainObject for specific DomainObject classes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.domain.model;

@Entity
@org.hibernate.annotations.Entity(selectBeforeUpdate = true)
@Table(name = "tbl_employee")
@TypeDefs(value = { @TypeDef(name = "dec", typeClass = DecimalUserType.class)})  // custom data type conversion

@NamedNativeQueries({
    @NamedNativeQuery(name = "HighSalary", query = "select * from tbl_employee where salary &amp;gt; :median_salary " , resultClass = Employee.class),
 @NamedNativeQuery(name = "LowSalary", query = "select * from tbl_employee where salary &amp;lt; :median_salary " ,  resultClass = Employee.class)
})

public class Employee extends MyAppDomainObject implements Serializable {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "employee_id")
    private Long id;
 
    @Column(name = "emp_code")
    private String accountCode;

    @Column(name = "manager_code")
    private String adviserCode;

 
 
    @Column(name = "type")
    @Enumerated(EnumType.STRING)
    private EmployeeType type = EmployeeType.PERMANENT;
 

    @Type(type = "dec")
    @Column(name = "base_salary")
    private Decimal salary = Decimal.ZERO;
 
    @Transient
    private Decimal salaryWithBonus; //not persisted to database
 
    @Formula("base_salary*2")
    private Decimal doubleSalary;   //derived or calculated read only property
 
    @Formula("(select base_salary where type = 'Permanent' )")
    private Decimal permanantLeaveLoading;   //derived or calculated read only property
 
 
    @OneToOne(cascade = { CascadeType.REFRESH })
    @JoinColumn(name = "emp_code", insertable = false, updatable = false)
    private EmployeeExtrInfo extraInfo;

    @ManyToOne(cascade = { CascadeType.REFRESH })
    @JoinColumn(name = "manager_code", insertable = false, updatable = false)
    private Manager manager;

    @OneToMany(cascade = { ALL, MERGE, PERSIST, REFRESH }, fetch = FetchType.LAZY)
    @JoinColumn(name = "emp_code", nullable = false)
    @Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
    private List&amp;lt;PaymentDetail&amp;gt; paymentDetails = new ArrayList&amp;lt;PaymentDetail&amp;gt;();

 //getters and setters omitted for brevity
 
}

&lt;/pre&gt;The dependency classes like EmployeeExtrInfo, Manager, and PaymentDetail will be mapped in a similar manner as the Employee class. The EmployeeType enum class is shown below. Also note the verys usefull annotations like @NamedNativeQueries, @TypeDefs, and @Formula. The @Formula marks a property as derived, or calculated, read-only property, where its value is calculated at fetch time using SQL expressions.  &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.domain.model;


public enum EmployeeType {
    
    PERMANENT("Permanent"),
    CONTRACTOR("Contractor"),
    CASUAL("Casual");
    
    private String type;
    
    private EmployeeType (String type) {
        this.type = type;
    }
    
    public String getType() {
        return this.type;
    }
}


&lt;/pre&gt;The "dec" is a custom data type, you need to define the custom data type class. The "salary" attribute will be making use of this special data type. This is ust a trivial example, but more powerful custom  type conversion classes can be created.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.domain.model;

import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;

import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;

public class DecimalUserType implements UserType, ParameterizedType {
    public static final int PRECISION = 28;
    public static final int SCALE = 15;

    public int[] sqlTypes() {
        return new int[]{Types.DECIMAL};
    }

    public Class&amp;lt;Decimal&amp;gt; returnedClass() {
        return BigDecimal.class;
    }

    public boolean equals(Object x, Object y) {
        if (x == y) {
            return true;
        }
        if (x == null || y == null) {
            return false;
        }
        return x.equals(y);
    }

    public int hashCode(Object x) {
        return 0;
    }

    public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws SQLException {
        BigDecimal forReading = rs.getBigDecimal(names[0]);

        if (forReading == null) {
            return null;
        }

        return forReading.setScale(2, RoundingMode.HALF_EVEN);   //round to 2 decimal places
    }


    public void nullSafeSet(PreparedStatement st, Object value, int index) throws SQLException {
        if (value == null) {
            st.setNull(index, Types.NUMERIC);
            return;
        }
  
  
        BigDecimal forSaving = (BigDecimal) value;
        st.setBigDecimal(index, forSaving.setScale(2, RoundingMode.HALF_EVEN));
    }

    public Object deepCopy(Object value) {
        return value;
    }

    public boolean isMutable() {
        return false;
    }

    public Serializable disassemble(Object value) {
        return null;
    }

    public Object assemble(Serializable cached, Object owner) {
        return null;
    }

    public Object replace(Object original, Object target, Object owner) {
        return original;
    }

    public void setParameterValues(Properties parameters) {
    }
}


&lt;/pre&gt;&lt;br /&gt;
The named queries are also shown above with the @NamedNativeQueries and @NamedNativeQuery annotations. The parametrized values like :median_salary needs to be supplied via the Hibernate repository class that makes use of the Employee domain object.  Firstly define the interface.  &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.domain.repo;

import java.util.List;


public interface EmployeeTableRepository {

 Employee saveEmployee(Employee employee) throws RepositoryException ; 
 Employee loadEmployee(Long employeeId) throws RepositoryException ;
 List&amp;lt;Employee&amp;gt; findAllEmployeesWithHighSalary(BigDecimal medianSalary) throws RepositoryException;
 List&amp;lt;Employee&amp;gt; findAllEmployeesWithLowSalary(BigDecimal medianSalary) throws RepositoryException 

}



&lt;/pre&gt;&lt;br /&gt;
Next the implementation of the above interface.  &lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.domain.repo;


@SuppressWarnings("unchecked")
public class EmployeeTableHibernateRepository extends HibernateDaoSupport implements EmployeeTableRepository {

    public EmployeeTableHibernateRepository (HibernateTemplate hibernateTemplate) {
        setHibernateTemplate(hibernateTemplate);
    }

 //The employee objects gets constructed and passed to repo via the Business Service layer
    public Employee saveEmployee(Employee employee) throws RepositoryException {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        session.saveOrUpdate(employee);
        session.flush();
        session.evict(employee);
        return this.loadEmployee(employee.getId());
    }
 
 public Employee loadEmployee(Long employeeId) throws RepositoryException {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        Criteria crit = session.createCriteria(Employee.class);
        crit.add(Restrictions.eq("id",employeeId));
        List&amp;lt;Employee&amp;gt; employees = crit.list();
        if (employees.size() == 1) {
            return employees.get(0);
        }
  
  //this is a custom exception class
        throw new RepositoryException("Found more than one or no employee with Id:" + employeeId);
    }
 
 
 public List&amp;lt;Employee&amp;gt; findAllEmployeesWithHighSalary(BigDecimal medianSalary) throws RepositoryException {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        Query query = session.getNamedQuery("HighSalary");    // query name defined in Employee class
        query.setBigDecimal(":median_salary", medianSalary);  // query parameter defined in Employee class 
        return (List&amp;lt;Employee&amp;gt;) query.list();
    }
 
 public List&amp;lt;Employee&amp;gt; findAllEmployeesWithLowSalary(BigDecimal medianSalary) throws RepositoryException {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        Query query = session.getNamedQuery("LowSalary");     // query name defined in Employee class
        query.setBigDecimal(":median_salary", medianSalary);  // query parameter defined in Employee class 
        return (List&amp;lt;Employee&amp;gt;) query.list();
    }

    
  //other methods can be defined here
}

&lt;/pre&gt;The Service classes shown below will be making use of the repository (or DAO) classes. The service class can use any number of the repository classes, and also responsible for cordinating the transaction as well with a TransactionManger. In the example below, we will be using the "&lt;b&gt;PlatformTransactionManager&lt;/b&gt;" implementation provided by the Spring framework.  &lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.service;

public interface EmployeeService {

   Employee saveEmployee(Employeee employee) throws RepositoryException;
   Employee loadEmployee(Long employeeId) throws RepositoryException;

}

&lt;/pre&gt;The implementation class is shown with the transaction manager. The employeeRepository and transactionManager are dependency injected   &lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.service;


import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
//....other imports

public class EmployeeServiceImpl implements EmployeeService {

    
    private final EmployeeTableRepository employeeRepository;
 private PlatformTransactionManager transactionManager;
   
    public EmployeeServiceImpl (EmployeeTableRepository employeeRepository, PlatformTransactionManager transactionManager) {
        this.employeeRepository = employeeRepository;
  this.transactionManager = transactionManager;
    }


    public Employee saveEmployee(Employeee employee) throws RepositoryException {
        TransactionStatus transactionStatus =
                transactionManager.getTransaction(new DefaultTransactionDefinition(
                        TransactionDefinition.PROPAGATION_REQUIRED));
        try {
            employee = this.employeeRepository.saveEmployee(employee);
        } catch (Exception e) {
            transactionManager.rollback(transactionStatus);
            throw new RepositoryException(e);
        } finally {
            if (!transactionStatus.isCompleted()) {
                transactionManager.commit(transactionStatus);
            }
        }
        return employee;
    }
 
 public Employee loadEmployee(Long employeeId) throws RepositoryException {
        return this.employeeRepository.loadEmployee(employeeId);
    }
 
 
 //....other methods

}

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How will you wire up the code snippet discussed above using Spring?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;The following 3 Spring configuration files are used for wiring up the classes defined above.&lt;b&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;
&lt;/b&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;The &lt;b&gt;daoContext.xml &lt;/b&gt;file to define the hibernate session factory, jndi data source, hibernate properties, and the user defined domain class and the repository.&lt;/li&gt;
&lt;li&gt;The&lt;b&gt; transactionContext.xml &lt;/b&gt;file to define the transaction manager.&lt;/li&gt;
&lt;li&gt;The &lt;b&gt;servicesContext.xml &lt;/b&gt;to define the custom services class&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
Firstly the &lt;b&gt;daoContext.xml &lt;/b&gt;file:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"&amp;gt;

 &amp;lt;bean id="dataSourceMyDB" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton"&amp;gt;
  &amp;lt;property name="jndiName"&amp;gt;
   &amp;lt;value&amp;gt;java:comp/env/jdbc/dataSource/mydb&amp;lt;/value&amp;gt;
  &amp;lt;/property&amp;gt;
 &amp;lt;/bean&amp;gt;

 &amp;lt;bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"&amp;gt;
  &amp;lt;property name="properties"&amp;gt;
   &amp;lt;props&amp;gt;
    &amp;lt;prop key="hibernate.dialect"&amp;gt;org.hibernate.dialect.SybaseDialect&amp;lt;/prop&amp;gt;
    &amp;lt;prop key="hibernate.generate_statistics"&amp;gt;false&amp;lt;/prop&amp;gt;
    &amp;lt;prop key="hibernate.hbm2ddl.auto"&amp;gt;verify&amp;lt;/prop&amp;gt;
    &amp;lt;prop key="hibernate.jdbc.batch_size"&amp;gt;50&amp;lt;/prop&amp;gt;
    &amp;lt;prop key="hibernate.show_sql"&amp;gt;false&amp;lt;/prop&amp;gt;
    &amp;lt;prop key="hibernate.format_sql"&amp;gt;false&amp;lt;/prop&amp;gt;
    &amp;lt;prop key="hibernate.cache.use_query_cache"&amp;gt;false&amp;lt;/prop&amp;gt;
    &amp;lt;prop key="hibernate.cache.use_second_level_cache"&amp;gt;false&amp;lt;/prop&amp;gt;
    &amp;lt;prop key="hibernate.query.factory_class"&amp;gt;org.hibernate.hql.classic.ClassicQueryTranslatorFactory&amp;lt;/prop&amp;gt;
   &amp;lt;/props&amp;gt;
  &amp;lt;/property&amp;gt;
  &amp;lt;property name="location"&amp;gt;
   &amp;lt;value&amp;gt;classpath:/hibernate.properties&amp;lt;/value&amp;gt;
  &amp;lt;/property&amp;gt;
 &amp;lt;/bean&amp;gt;
 
    &amp;lt;bean id="hibernateAnnotatedClasses" class="org.springframework.beans.factory.config.ListFactoryBean"&amp;gt;
        &amp;lt;property name="sourceList"&amp;gt;
            &amp;lt;list&amp;gt;
                &amp;lt;value&amp;gt;com.myapp.domain.model.Employee&amp;lt;/value&amp;gt;
            &amp;lt;/list&amp;gt;
        &amp;lt;/property&amp;gt;
    &amp;lt;/bean&amp;gt;

 &amp;lt;bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&amp;gt;
  &amp;lt;property name="dataSource" ref="dataSourceShadow" /&amp;gt;
  &amp;lt;property name="hibernateProperties"&amp;gt;
   &amp;lt;ref local="hibernateProperties" /&amp;gt;
  &amp;lt;/property&amp;gt;
  &amp;lt;property name="entityInterceptor"&amp;gt;
        &amp;lt;/property&amp;gt;
  &amp;lt;property name="annotatedClasses"&amp;gt;
      &amp;lt;ref local="hibernateAnnotatedClasses" /&amp;gt;
  &amp;lt;/property&amp;gt;
  &amp;lt;property name="annotatedPackages"&amp;gt;
   &amp;lt;list&amp;gt;&amp;lt;/list&amp;gt;
  &amp;lt;/property&amp;gt;
 &amp;lt;/bean&amp;gt;
 
 &amp;lt;bean id="daoTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"&amp;gt;
  &amp;lt;constructor-arg index="0" ref="sessionFactory" /&amp;gt;
  &amp;lt;constructor-arg index="1" value="true" /&amp;gt;
 &amp;lt;/bean&amp;gt;

 &amp;lt;!-- Repository beans --&amp;gt;
 &amp;lt;bean id="employeeTableRepository" class="com.myapp.domain.repo.EmployeeTableHibernateRepository"&amp;gt;
  &amp;lt;constructor-arg ref="daoTemplate" /&amp;gt;
 &amp;lt;/bean&amp;gt;
 
&amp;lt;/beans&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The &lt;b&gt;transactionContext.xml &lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"&amp;gt;

    &amp;lt;!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) --&amp;gt;
    
    &amp;lt;alias name="hibernateSessionFactory" alias="sessionFactory"/&amp;gt;
       
    &amp;lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&amp;gt;
        &amp;lt;property name="sessionFactory" ref="sessionFactory" /&amp;gt;
    &amp;lt;/bean&amp;gt;
    &amp;lt;bean id="advisorAutoProxy" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" /&amp;gt;
    &amp;lt;bean id="transactionAttrSource" class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor"&amp;gt;
        &amp;lt;property name="transactionInterceptor" ref="transactionInterceptor" /&amp;gt;
    &amp;lt;/bean&amp;gt;
    &amp;lt;bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"&amp;gt;
        &amp;lt;property name="transactionManager" ref="transactionManager" /&amp;gt;
        &amp;lt;property name="transactionAttributeSource"&amp;gt;
            &amp;lt;bean class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource" /&amp;gt;
        &amp;lt;/property&amp;gt;
    &amp;lt;/bean&amp;gt;

&amp;lt;/beans&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Finally the &lt;b&gt;servicesContext.xml&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-2.5.xsd
   http://www.springframework.org/schema/aop 
   http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"&amp;gt;

 &amp;lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --&amp;gt;
 &amp;lt;!-- CONFIGURE SERVICE BEANS         --&amp;gt;
 &amp;lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --&amp;gt;
 &amp;lt;bean id="employeeService" class="com.myapp.service.EmployeeService"&amp;gt;
  &amp;lt;constructor-arg ref="employeeTableRepository" /&amp;gt;
  &amp;lt;constructor-arg ref="transactionManager" /&amp;gt;
 &amp;lt;/bean&amp;gt;
 
&amp;lt;/beans&amp;gt;

&lt;/pre&gt;&lt;b&gt;Q.&lt;/b&gt; How will you go about writing an integration or unit test for the &lt;i&gt;EmployeeService &lt;/i&gt;described above? &lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;Since the dataSource is looked up via JNDI, you need to emulate the JNDI lookup.&amp;nbsp; This can be achieved with the Spring helper classes &lt;b&gt;SimpleNamingContextBuilder &lt;/b&gt;and &lt;b&gt;DriverManagerDataSource&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
This involves 3 steps.&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt; Define a bootsrapper class that emulates JNDI lookup using Spring helper classes like &lt;i&gt;SimpleNamingContextBuilder &lt;/i&gt;and &lt;i&gt;DriverManagerDataSource&lt;/i&gt;. For example, &lt;b&gt;SybaseDevBootstrapper.java&lt;/b&gt; file.&lt;/li&gt;
&lt;li&gt;Wire-up this via a Spring config file named &lt;b&gt;sybaseDevBootstrapContext.xml&lt;/b&gt;. &lt;/li&gt;
&lt;li&gt;Finally, write the JUnit test class&lt;b&gt; EmployeeServicesSybTest.java&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;Define the &lt;b&gt;TestExecutionListeners &lt;/b&gt;if required. &lt;/li&gt;
&lt;/ul&gt;&amp;nbsp;Firstly the &lt;b&gt;SybaseDevBootstrapper.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.test.db;

import javax.naming.NamingException;

import org.springframework.beans.factory.BeanCreationException;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;

/**
 * helper class to bootstrap the sybase database datasources
 */
public class SybaseDevBootstrapper  {
    
 public static final String JNDI_BINDING_DB = "java:comp/env/jdbc/dataSource/mydb";
    public static final String DRIVER_CLASS = "com.sybase.jdbc3.jdbc.SybDriver";

 private SimpleNamingContextBuilder builder;  //Spring JNDI emulator class

 /**
  * setup sybase databases, and bind to specific places in jndi tree
  */
 public void start() {
        try {
         builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();

         DriverManagerDataSource ds = new DriverManagerDataSource();
            ds.setDriverClassName(DRIVER_CLASS);
            ds.setUrl("jdbc:sybase:Tds:host-name:10004/my_db");
            ds.setUsername("user");
            ds.setPassword("pwd");
            builder.bind(JNDI_BINDING_DB, ds);
            
            
        } catch (NamingException e) {
            throw new BeanCreationException(e.getExplanation());
        }
    }
 
 public void stop() {
  builder.deactivate();
  builder.clear();
 }
}


&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Next, wire the above Java class.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-2.5.xsd"
 default-autowire="byName"&amp;gt;

 &amp;lt;bean id="sybaseDevBootstrapper" class="com.myapp.test.db.SybaseDevBootstrapper" init-method="start" destroy-method="stop"/&amp;gt;

&amp;lt;/beans&amp;gt;


&lt;/pre&gt;&lt;br /&gt;
Finally the test class &lt;b&gt;EmployeeServicesSybTest.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp.test.services;

import javax.annotation.Resource;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;

//...other imports


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
  "classpath:/sybaseDevBootstrapContext.xml",
  "classpath:/transactionContext.xml",
  "classpath:/daoContext.xml",
  "classpath:/servicesContext.xml",
})
@TestExecutionListeners(value = { 
  DependencyInjectionTestExecutionListener.class,
  SessionBindingHibernateListener.class
})

public class EmployeeServicesSybTest {
 
 @Resource
 EmployeeService employeeService;
    
    @Test
    public void testSaveEmployee() throws RepositoryException {
      Assert.assertTrue(employeeService != null);
      
      Employee employee = new Emloyee();
      //....assign values here
      
      employeeService.seaveEmployee(employee);
      
    }

}&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The JUnit's way of setting up cross cutting concerns like security, locale, currency, timezone, and any other pre-initilization rules for the test cases function correctly is via annoattions like @Before and @After. The Spring's TestContext framework uses the  anootation @TestExecutionListeners to acheive setting up of these cross cutting concerns. In the above example, we are using the DependencyInjectionTestExecutionListener.class from the Spring framework to provide support for dependncy injection and the custom SessionBindingHibernateListener.class to bind the session to the current thread. The custom implementation shown below extends the AbstractTestExecutionListener, which is the abstract implementation of TestExecutionListener class from the Spring framework.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;

/**
 * Helper class for binding sessions to the current thread
 * 
 */
public class SessionBindingHibernateListener extends SessionBindingListener {
    
 private static final String BEAN_NAME = "hibernateSessionFactory";

 public SessionBindingHibernateListener() {
  super(BEAN_NAME);
 }
}


&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;

import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.AbstractTestExecutionListener;
import org.springframework.transaction.support.TransactionSynchronizationManager;


/**
 * Helper class for binding sessions to the current thread
 * 
 */
public class SessionBindingListener extends AbstractTestExecutionListener {
    
    private final String beanName;
    
 public SessionBindingListener(String beanName) {
  this.beanName = beanName;
 }
    
 @Override
 public void prepareTestInstance(TestContext testContext) throws Exception {
  ApplicationContext context = testContext.getApplicationContext();
  SessionFactory sessionFactory = (SessionFactory) context.getBean(beanName);
  
        Session session = SessionFactoryUtils.getSession(sessionFactory, true);
        session.setFlushMode(FlushMode.MANUAL);
        if (!TransactionSynchronizationManager.hasResource(sessionFactory)) {
            TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
        }
 }
}


&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-7062161203125898355?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/_GcK7Mh4nb_RrUe2Qy6wztlDKeM/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/_GcK7Mh4nb_RrUe2Qy6wztlDKeM/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/_GcK7Mh4nb_RrUe2Qy6wztlDKeM/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/_GcK7Mh4nb_RrUe2Qy6wztlDKeM/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/B-Fgx_r6R_Y" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/7062161203125898355/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=7062161203125898355" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/7062161203125898355?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/7062161203125898355?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/B-Fgx_r6R_Y/hibernate-interview-q-with-annotations.html" title="Hibernate Interview Questions and Answers: with annotations and Spring framework" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://java-success.blogspot.com/2012/01/hibernate-interview-q-with-annotations.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DUIEQXY7fyp7ImA9WhRUFk8.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-4318413847531496683</id><published>2012-01-26T17:18:00.000-08:00</published><updated>2012-01-26T17:25:00.807-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-26T17:25:00.807-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript interview answers" /><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript interview questions" /><title>JavaScript Interview Questions and Answers: Coding and putting all together</title><content type="html">&lt;b&gt;Q. How would you go about implementing a mechanism to log clien-side JavaScript errors to the server-side log?&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; Generally a Web application will log any exceptions that occur during server-side processing. These logs are key in identifying and debugging issues with the application. But when you build rich client-side applications with lots of JavaScript code, it is really worth implementing a mechanism to log all the client side errors to the server side. The following code sample demonstrates an AJAX POST being made from the client side to the server side with the data -- error msg, the URL of the JavaScript file, and the line number where the error occured.  &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;(function () {
    'use strict'; // throws more xecpetions, prevents, or throws errors, when relatively "unsafe" actions are taken such as accessing global object, 
                 // and disables features that are confusing or poorly thought out.

  //Return if the project and module are already present
  if (window.MYPROJECT &amp;amp;&amp;amp; window.MYPROJECT.errorHandler) {
   return;
  }
 
 // Create MYPROJECT namespace if does not exist
  if (!window.MYPROJECT) {
   window.MYPROJECT = {};
  }
 
  // Create MYPROJECT.errorHandler namespace if does not exist
  if (!window.MYPROJECT.errorHandler) {
   window.MYPROJECT.errorHandler =  (function () {
 
    var config, init, logError;                             
 
    config = {
     timeout: '5000',
     errorLogURL: '/ApplicationName/LogError'   //default URL 
    };
 
    /**
     * private function to register the logError handler
     */
    init = function (errorLogURL) {
     window.onerror = logError;                                           //the onerror event on windows invoke the logerror function
     config.errorLogURL = errorLogURL || config.errorLogURL;   // if not defined use default URL
    };
 
    /**
     * private function to log error
     */
    logError = function (msg, url, lineNo) {
     
    //makes an ajax post to the server using the jQuery library
     jQuery.ajax({
      url: config.errorLogURL,                                  //URL for the AJAX POST 
      type: 'POST',
      data: {'msg' : msg, 'url' : url, 'lineNo' : lineNo},  //log msg, the URL of the .js file containing the error, and the line number of the error
      timeout: config.timeout
     });
 
     return false;
    };
 
            //public methods that can be invoked from outside 
    return { init: init, logError: logError };
   
   }());
  }
}());

&lt;/pre&gt;&lt;br /&gt;
The above code can be used as follows.&lt;br /&gt;
&lt;br /&gt;
STEP1: Initialize when the document loads&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;jQuery(document).ready(function () {
 'use strict';
 MYPROJECT.ajaxErrorHandler.init('/myapp/logError');
});
&lt;/pre&gt;&lt;br /&gt;
STEP2: Log the error where required&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;if(someErrorCondition) {
    MYPROJECT.errorHandler.logError('Error message is .... ', 'test.js','36');
}
&lt;/pre&gt;&lt;br /&gt;
or&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;try {
    //some logic
} catch (ex) {
       MYPROJECT.errorHandler.logError(ex.message, ex.fileName, ex.lineNumber);
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
On the serverside, you could write a Java Servlet to recieve and process this ajax request by writing to the serevr log using a library like log4j.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package somepkg;
 
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class ErrorLoggingServlet extends HttpServlet {

 private static Logger logger = Logger.getLogger(ErrorLoggingServlet.class);

  public void service(HttpServletRequest req, HttpServletResponse res)
             throws ServletException, IOException {
  
        //extract the request parameters  
  String msg = req.getParameter("msg");
  String file = req.getParameter("url");
  String lineNo = req.getParameter("lineNo");

   // extract the user-agent, ie browser.
   String userAgent = req.getHeader("user-agent");
        
  //log the client-side error to the server side log file
  logger.error(String.format("JSError: %s \n%s(Line:%s)\nBrowser: %s",
    trim(msg), trim(file), trim(lineNo), trim(userAgent)));
 }
 
 /**
   * Trim the input parameters before logging to avoid unfiltered input 
  * from the client side filling up the log files.
  */
  private String trim(String in) {
  return (in != null) ? in.substring(0, 100) : "";
  }
}

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How would you go about making an AJAX call using a JavaScript framework like jQuery to retrieve json data?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; The sample code below uses 3 files&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;test3.html -- The html file with the button to click&lt;/li&gt;
&lt;li&gt;test3.js   -- The JavaScript file that makes use of the jQuery framework to make the AJAX call.&lt;/li&gt;
&lt;li&gt;test3.json -- The json data file containing data to be retrieved via AJAX requests.  &lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
Firstly, the test3.html &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&amp;gt;
&amp;lt;script language="javascript" type="text/javascript" src="jquery-1.4.2.js"&amp;gt;
&amp;lt;/script&amp;gt;
&amp;lt;script language="javascript" type="text/javascript" src="test3.js"&amp;gt;
&amp;lt;/script&amp;gt;


&amp;lt;title&amp;gt;Insert title here&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;form&amp;gt;  
Click the button to fetch json data:  
     &amp;lt;input id="go" type="button" value="go"/&amp;gt;  
  &amp;lt;/form&amp;gt;

&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
Note that jquery-1.4.2.js is jQuery library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Next, the the test3.json file&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;{"data" :
 { 
  "topics": 
          [
              "Java",
     "JEE",
     "JavaScript",
     "Unix"
          ]
 }
} 

&lt;/pre&gt;&lt;br /&gt;
Finalyy, the test3.js&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$(document).ready(function(){
  $('input#go').click(function() {
 $.ajax({
  type: "GET",
  url: "http://localhost:8080/webdav/test3.json",
     beforeSend: function(xhr){
          if (xhr.overrideMimeType)
         {
           xhr.overrideMimeType("application/json");
         }
       },
   dataType: "JSON",
 

  success: function(data) {
     console.log(data);
           var obj = jQuery.parseJSON(data);
     alert(obj.data.topics);
  } 
    
  
 });
  
  });
});

&lt;/pre&gt;&lt;br /&gt;
To run the above sample files, you need an HTTP Web server. I downloaded and installed the tomcat server (version 5), and copied the above 3 files to the sample webapp that comes with the installation. The copied folder is &amp;lt;tomcat-home&amp;gt;/webapps/webdav. The "webdav" is the web appplication context. Copy the 3 files to "webdav". Start the tomcat server via  &amp;lt;tomcat-home&amp;gt;/bin/startup.bat (or startup.sh for Unix). You can now open up a browser like Firefox and enter the URL as http://localhost:8080/webdav/test3.html invoke test3.html. Click on the button, and you will the json data getting alerted.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You could also check the webconsole in Firefox via Tools --&amp;gt; Web Developer --&amp;gt; Web Console  (available in version 4.0 onwards). Also, download the Firebug plugin, and open the plugin. Go to the "Net" and then "XHR" tab in the plugin to view the AJAX requests being made. Also, feel free to get more familarized with the firebug, which is very handy for debugging your Web application on client side.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div style="background-color: white; color: #38761d;"&gt;&lt;span style="font-size: large;"&gt;More JavaScript Q&amp;amp;A&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_10.html"&gt;JavaScript Q&amp;amp;A: Working with the objects&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_8908.html"&gt;JavaScript Interview Q&amp;amp;A: Closure&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_8681.html"&gt;JavaScript Interview Q&amp;amp;As: Function.call, Function.apply, and Callback functions&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_26.html" target="_blank"&gt;JavaScript Q&amp;amp;A: Coding&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-4318413847531496683?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/C493vVy_8qA0ywO5N35D7aTB3QI/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/C493vVy_8qA0ywO5N35D7aTB3QI/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/C493vVy_8qA0ywO5N35D7aTB3QI/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/C493vVy_8qA0ywO5N35D7aTB3QI/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/f_OoRGJtZqE" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/4318413847531496683/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=4318413847531496683" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/4318413847531496683?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/4318413847531496683?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/f_OoRGJtZqE/javascript-interview-questions-and_26.html" title="JavaScript Interview Questions and Answers: Coding and putting all together" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_26.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DUANSXw-fyp7ImA9WhRUE0U.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-1943887859478801557</id><published>2012-01-23T22:49:00.000-08:00</published><updated>2012-01-23T22:49:58.257-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-23T22:49:58.257-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="UNIX interview answers" /><category scheme="http://www.blogger.com/atom/ns#" term="UNIX interview questions" /><title>UNIX Interview questions and answers</title><content type="html">In Core Java Career Essentials book, I had covered some of the core UNIX commands that are useful to Java developers with practical and real life examples. This blog expands on it with some handy UNIX features to complement the book.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. &lt;/b&gt;Where would you use the control operators like ";", "&amp;amp;&amp;amp;", and "||" in UNIX?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;These control operators are used to combine different commands in a single line. There is a difference between the characters in a sense how the subsequent commands are executed. For example, &lt;br /&gt;
&lt;br /&gt;
The following commands use a ";" to separate commands. This means both the commands will be executed regardless of the first command is successful (i.e. exit code of 0) or not  (i.e. exit code other than 0);&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$ cd Temp; echo $(pwd)
&lt;/pre&gt;&lt;br /&gt;
You could get an output shown below if there is folder named Temp.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;/c/Temp
&lt;/pre&gt;&lt;br /&gt;
If the folder named Temp is not present, you will get an error and the current directory printed.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;sh: cd: Temp: No such file or directory
/c
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
So, what if you want to only print the current directory if the first change directory command is successful? This is where the "&amp;amp;&amp;amp;" operator comes in handy.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$ cd Temp &amp;amp;&amp;amp; echo $(pwd)
&lt;/pre&gt;&lt;br /&gt;
In the above example, the echo command will only be excuted if the change directory command is successful. If not successful, only an error will be thrown, and the current directory will not be printed. There are situations where&lt;br /&gt;
you might want to do the reverse. That is, execute the second command only if the first command fails. For example, make a  "Temp" directory only if the change directory fails. This where the "||" operator comes in handy.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$ cd temp ||  mkdir temp &amp;amp;&amp;amp; cd temp  &amp;amp;&amp;amp; echo $(pwd)
&lt;/pre&gt;&lt;br /&gt;
If, temp directory is not found, make a new directory named temp, and if make direcory is successful, change to that directory and echo the current directory. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; What do you uderstand by 2&amp;gt;&amp;amp;1 in UNIX?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; In UNIX you have STDIN, which is denoted by number 0, STDOUT, which is denoted by 1, and STDERR, which is denoted by 2. So, the above line means, the error messages go to STDERR, which is redirected to STDOUT. So, the error messages go to where ever the STDOUT goes to. For example, The following command creates a multiple directories for a maven based Java project. if the the directory creation is successful, change directory to "project" and print the directory tree structure. The STDOUT and  STDERR are directed to the file named  maven-project.log under the project folder. &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$ mkdir -p project/{src/{main/{java,resources},test/{java,resources}}} &amp;amp;&amp;amp; cd project ; find . -type  d -print  &amp;gt; maven-project.log
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The output will be something like&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;.
./src
./src/main
./src/main/java
./src/main/resources
./src/test
./src/test/java
./src/test/resources
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; What is /dev/null?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; It is a blackhole. For example,  in the earlier example, if you want to ignore error like "sh: cd: Temp: No such file or directory" being printed, you can redirect your output to /dev/null. For example&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$ cd temp &amp;gt; /dev/null 2&amp;gt;&amp;amp;1 &amp;amp;&amp;amp; echo $(pwd)
&lt;/pre&gt;&lt;br /&gt;
will fail silently and nothing will be printed if there is no "temp" folder. The message has gone into the blackhole. If there is a "temp" folder, the present working directory (i.e. pwd) will be printed out.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. &lt;/b&gt;How would you go about the following scenario -- You had to move to another directory temporarily to look at a file, and then move back to the directory where you were?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; One way is to start with "/c/Temp" folder&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$ cd ../projects/JMeter
$ cd ../../Temp
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The better way is to use the &lt;b&gt;pushd &lt;/b&gt;and &lt;b&gt;popd &lt;/b&gt;commands. These commands make use of a "stack" data structure using the "Last In First Out" approach.&lt;br /&gt;
&lt;br /&gt;
changes to the /c/Projects/JMeter folder and prints the stack&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$ pushd ../projects/JMeter
&lt;/pre&gt;&lt;br /&gt;
The stack is printed as shown below.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;/c/projects/JMeter /c/Temp
&lt;/pre&gt;&lt;br /&gt;
The /c/projects/JMeter will be popped out of the stack and the directory will change back to /c/Temp&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$ popd
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
If you want pushd to not print the stack, you could direct the output to the black hole /dev/null as shown below.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$ pushd ../projects/JMeter &amp;gt; /dev/null
&lt;/pre&gt;&lt;br /&gt;
The above is a trivial example, but in real life, you may want to navigate between more number of directories and this stack based approach will come in very handy without having to use the "cd" command. Also, very useful in UNIX scripts. Use it astutely without having to build up a gigantic directory stack full of useless directories.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; In UNIX, only nine command line arguments can be accessed using positional parameters. How would you go about having access to more than 9 argumnets?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; Using the shift command. For example, in unix, when you run a command like &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$ sh test-bash.sh file1 file2 file3 file4 file5 file6 file7 file8 file9, file10, fil11
&lt;/pre&gt;&lt;br /&gt;
The ${0} is test-bash.sh, and ${1} is file1, ${2} file2 and so on till ${9}, which is file9. In the program, if you want to access file10 after processing file1 to file9, you need to use the "shift" command.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$ shift
&lt;/pre&gt;&lt;br /&gt;
All it does is move all the command line arguments to the left by 1 position. Which means the file1 will be moved out, and file2 becomes ${1} and file10 becomes ${2}. If you shift it agian, the file3 becomes ${1} and file11 becomes ${9}. In a nutshell&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
${#} -  Total number of arguments&lt;br /&gt;
${0} -   Command or the script name&lt;br /&gt;
${1},${2}, ${3} - First, second and third args respectively.&lt;br /&gt;
${*} -   All the command line arguments starting from $1.&lt;br /&gt;
${@} - Same as ${*} except when it is quoted "${@}" will pass the positional parameters unevaluated. For example, echo "${@}" will print&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;echo "$1" "$2" ...
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How will you go about writing a UNIX shell script, that reads one or more data files like the one shown below and perform a particular task like logging the information in the file or making database calls to patch some data? &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The &lt;b&gt;test-data.txt&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;Server Name:Database Name:username: password
Line2-file-name1.sql
Line2-file-name2.sql
Line2-file-name3.sql
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The usage of the script will be something like&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$ sh test-bash.sh test-data.txt test-data2.txt test-data3.txt
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; The sample script below will be predominantly making use of the commands discussed above. If not clear, try to read and understand the above Q&amp;amp;As. The best way to learn is to try it out yourself. The lines starting with "#" are comments. If you do not have a UNIX environment, download a windows UNIX emularor like MSYS or CYGWIN to run it on your WINTEL platform.&lt;br /&gt;
&lt;br /&gt;
The &lt;b&gt;test-bash.sh.&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;#!/bin/bash

# usage is --&amp;gt;  sh Temp/test-bash.sh Temp/test-data.txt
# ${0} is  Temp/test-bash.sh 
# ${1} is  Temp/test-data.txt

echo No of arguments:  ${#}
echo Arguments are: ${*}
echo Arguments are: ${@}

#usage sub function that gets invoked by the main function.
#Echo the usage pattern and exit the script.   
usage () {
 echo Usage : $(basename ${0}) file
 exit 1
}


#log sub function that gets invoked by the main function.
log () {
 echo ${@}
 echo ${@} &amp;gt;&amp;gt; ${LOGFILE}
}


#-r means FILE exists and is readable. 
#If the file does not exists or not readable, invoke the "usage" sub routine  to print the usage
[[ -r ${1} ]] || usage


#dirname prints the directory &amp;amp; basename prints the file-name
echo script directory name is: $(dirname ${0})   #
echo script-name is:   $(basename ${0}) 
echo data directory name is: $(dirname ${1})
echo data-file-name is:   $(basename ${1}) 

CMDFILE=$(basename ${1})

#this will be test-data.txt.log
LOGFILE=$(basename ${1}).log

#  take the first line in the data file and
#  translate ':" to ' ' (i.e. translate colon to empty space) 
COMMAND=($(head -1 ${1} | tr ':'  ' '))

#log the first line values in the data file 
#separate with a comma
log ${COMMAND[0]},${COMMAND[1] },${COMMAND[2]}


pushd $(dirname ${1}) &amp;gt; /dev/null

#log an empty line
log

#log start timestamp
log BEGIN $(date)


for SQLFILE in $(sed -n '2,$p' ${CMDFILE}); do
 log  ${SQLFILE}
 # in real life execute the sql commands using an interactive SQL command. For example
 # isql -S ${COMMAND[0]} -D ${COMMAND[1]} -U ${COMMAND[2]} -P ${COMMAND[3]} &amp;lt; ${SQLFILE} &amp;gt; ${LOGFILE} 2&amp;gt;&amp;amp;1
done

#log end time stamp
log END $(date)

popd &amp;gt; /dev/null

# if more data files are supplied as commandline arguments shift so that second file becomes ${1} and so on
shift

#If more filenames are supplied in the commandline arguments, repeat the script for the successive filenames.
[[ ${@} ]] &amp;amp;&amp;amp; ${0} ${@}

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The output for&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$ sh test-bash.sh test-data.txt
&lt;/pre&gt;&lt;br /&gt;
will be&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;No of arguments: 1
Arguments are: test-data.txt
Arguments are: test-data.txt
script directory name is: .
script-name is: test-bash.sh
data directory name is: .
data-file-name is: test-data.txt
Server,Name,Database

BEGIN Tue Jan 24 12:57:16 AUSEDT 2012
Line2-file-name1.sql
Line2-file-name2.sql
Line2-file-name3.sql
END Tue Jan 24 12:57:16 AUSEDT 2012

&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-1943887859478801557?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/hBfc4KsmNWqaZ_uswC_Qc691y1Q/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/hBfc4KsmNWqaZ_uswC_Qc691y1Q/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/hBfc4KsmNWqaZ_uswC_Qc691y1Q/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/hBfc4KsmNWqaZ_uswC_Qc691y1Q/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/CDz1QufYGbg" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/1943887859478801557/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=1943887859478801557" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/1943887859478801557?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/1943887859478801557?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/CDz1QufYGbg/unix-interview-questions-and-answers.html" title="UNIX Interview questions and answers" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2012/01/unix-interview-questions-and-answers.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DUMBRng8eSp7ImA9WhRUFk8.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-4072308294699691202</id><published>2012-01-10T17:16:00.000-08:00</published><updated>2012-01-26T17:24:17.671-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-26T17:24:17.671-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript interview answers" /><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript interview questions" /><title>JavaScript Interview Questions and Answers: Function.call, Function.apply, and Callback functions</title><content type="html">&lt;b&gt;Q. What are the different ways to invoke a function?&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; The functions can be invoked via one of the following 5 ways&lt;br /&gt;
&lt;br /&gt;
&lt;ol&gt;&lt;li&gt;function_name(param1, param2, etc); --&amp;gt; "this" refers to global object like window.&lt;/li&gt;
&lt;li&gt;obj1.function_name(param1,param2,etc);&amp;nbsp; --&amp;gt; "this" refers to obj1.&lt;/li&gt;
&lt;li&gt;The constructor.&lt;/li&gt;
&lt;li&gt;function_name.&lt;b&gt;call&lt;/b&gt;(objRef, param1);&amp;nbsp;&amp;nbsp;&amp;nbsp; //remember that the functions in JavaScript is like an object and it has it's own methods like toString(..), call(...), apply(...), etc.&lt;/li&gt;
&lt;li&gt;function_name.apply(objRef, params[parama1,param2, etc]); &lt;/li&gt;
&lt;/ol&gt;&lt;br /&gt;
So, why use&amp;nbsp; function_name.&lt;b&gt;call&lt;/b&gt;(...) or function_name.&lt;b&gt;apply&lt;/b&gt;( ... ) as opposed to just function_name( ... )? Let's look at this with some examples.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var x = 1;           //global variable x;

var obj1 = {x:3};   //obj1 variable x
var obj2 = {x:9};   //obj2 variable x

function function_name(message) {
   alert(message + this.x) ;
}


function_name("The number is ");              //alerts the global x --&amp;gt; The number is 1

//the first argument is the obj reference on which to invoke the function, and the
//the second argument is the argument to the function call
function_name.call(obj1, "The number is ");   //alerts the obj1's x --&amp;gt; The number is 3
function_name.call(obj2, "The number is ");   //alerts the obj2's x --&amp;gt; The number is 5



//the first argument is the obj reference on which to invoke the function, and the
//the second argument is the argument to the function call as an array
function_name.apply(obj1, ["The number is "]);   //alerts the obj1's x --&amp;gt; The number is 3
function_name.apply(obj2, ["The number is "]);   //alerts the obj2's x --&amp;gt; The number is 5

&lt;/pre&gt;&lt;br /&gt;
The purpose is of call and apply methods are&amp;nbsp; to invoke the function for any object without being bound to an instance of the this object. In the above example, the this object is the global object with the x value of 1. &amp;nbsp; In a function called directly without an explicit owner object, like &lt;code&gt;function_name()&lt;/code&gt;, causes the value of &lt;code&gt;this&lt;/code&gt; to be the default object (&lt;b&gt;&lt;code&gt;window&lt;/code&gt; &lt;/b&gt;in the browser).  The call and apply methods allow you to pass your own object to be used as the "this" reference. In the above example, the obj1 and obj2 were used as "this" reference.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. What will be the alerted message for buttons 1-5 shown below?&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The test.html stored under js_tutorial/html&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&amp;gt;

&amp;lt;title&amp;gt;Insert title here&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;form id="someform"&amp;gt;
       &amp;lt;input id="btn1" type="button" value="click-me1"/&amp;gt;  
       &amp;lt;input id="btn2" type="button" value="click-me2"/&amp;gt; 
       &amp;lt;input id="btn3" type="button" value="click-me3" onclick="buttonClicked()"/&amp;gt;  
       &amp;lt;input id="btn4" type="button" value="click-me4"/&amp;gt;  
       &amp;lt;input id="btn5" type="button" value="click-me5"/&amp;gt;  
    &amp;lt;/form&amp;gt;
    
    &amp;lt;script language="javascript" type="text/javascript" src="../js/test.js"&amp;gt;
    &amp;lt;/script&amp;gt;
    
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
The test.js stored under js_tutorial/js.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;function buttonClicked(){  
    var text = (this === window) ? 'window' : this.id;  
    alert( text );  
}  

var button1 = document.getElementById('btn1');  
var button2 = document.getElementById('btn2');  
var button4 = document.getElementById('btn4');  
var button5 = document.getElementById('btn5');  

button1.onclick = this.buttonClicked; //or just  button1.onclick = buttonClicked; 
button2.onclick = function(){   
 buttonClicked();   
};  

button4.onclick =  function(){   
 buttonClicked.call(button4);   
};  

button5.onclick =  function(){   
 buttonClicked.apply(button5);   
}; 

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;The "this" object passed to the buttonClicked function are as follows:&lt;br /&gt;
&lt;br /&gt;
click-me1 --&amp;gt; btn1 ("btn1" because it's a method invocation and this will be assigned the owner object - the button input element)&lt;br /&gt;
click-me2 --&amp;gt; window (This is the same thing as when we assign the event handler directly in the element's tag as in click-me3 button)&lt;br /&gt;
click-me3 --&amp;gt; window (global object) &lt;br /&gt;
click-me4 --&amp;gt; btn4&lt;br /&gt;
click-me5 --&amp;gt; btn5&lt;br /&gt;
&lt;br /&gt;
When defining event handlers via frameworks likejQuery, the library will take care of overriding the value of "this" reference to ensure that it contains a reference to the source of the event element. For example,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$('#btn1').click( function() {  
     var text = (this === window) ? 'window' : this.id;  //// jQuery ensures 'this' will be the btn1
    alert( text );  
});  
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The jQuery makes use of apply() and call() method calls to achieve this.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. What will be the output for the following code snippet?&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&amp;gt;

&amp;lt;title&amp;gt;Insert title here&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;form id="someform"&amp;gt;
       &amp;lt;input id="btn1" type="button" value="click-me1" onclick="test()"/&amp;gt;  
    &amp;lt;/form&amp;gt;
    
    &amp;lt;script language="javascript" type="text/javascript" src="../js/test2.js"&amp;gt;
    &amp;lt;/script&amp;gt;
    
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
the test2.js file.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var myobj1 = {  
  x:9, 
  myfunction:function(){
 
    if(this === window) 
     alert("x is not Defined");
 else if (this === myobj1)
     alert(this.x);
 else 
  alert("Error!");
  }
}


function test(){
 setTimeout(myobj1.myfunction, 1000);
}

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; The output in the alert will be "x is not defined". This is because the "this" will be referring to the default global object -- window. The above code can be fixed by replacing the test() function as shown below.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;function test(){
 setTimeout(function(){
  myobj1.myfunction()}, 
 1000); 
}&lt;/pre&gt;&lt;pre class="brush: csharp"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre class="brush: csharp"&gt;&lt;b&gt;Note&lt;/b&gt;: The setTimeout(..,..) method alerts only after 1 second of clicking the button.
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; What is a &lt;b&gt;callback &lt;/b&gt;function? Why would you need callback functions?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; As mentioned earlier, the functions in JavaScript are actually objects. For example,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var functionAdd = new Function("arg1", "arg2", "return arg1 * arg2;");
functionAdd(5,9);  // returns 14
functionAdd(2,3);  // returns 5

&lt;/pre&gt;&lt;br /&gt;
So, the functions can be passed as arguments to other functions and invoked from other functions. For example,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;function functionAdd(arg1, arg2, callback) {
  var result = arg1 + arg2 
  // Since we're done, let's call the callback function and pass the result
  callback(result);
}

 
// call the function
functionAdd(5, 15, function(result) {
    // this anonymous function will run when the callback is called
 console.log("callback called! " + result);
}); 

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Why invoke the callback function when the functionAdd(..) could have executed the results?&lt;/b&gt; Client-side is predominantly asynchronous with following types of events.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;UI Events&lt;/b&gt; like mouse click, on focus, value change, etc. These events are asynchronous because you don't know when a user is going to click on a button. So, callback functions need to be invoked when a button is clicked. For example JavaScript frameworks like jQuery quite often uses callback functions. Whether handling an event, iterating a collection of nodes, animating an image, or applying a dynamic filter, callbacks are used to invoke your custom code at the appropriate time. &lt;br /&gt;
&lt;br /&gt;
The test.js.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$(document).ready(function(){
  $("button").click(function(){
    $("p").hide(2000,function(){
    console.log("Inside the callback function...");
   //called 2 seconds after the paragraph is hidden 
      alert("The paragraph is now hidden");
    });
  });
});

&lt;/pre&gt;&lt;br /&gt;
The test.html&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;script type="text/javascript" src="jquery.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script type="text/javascript" src="test.js"&amp;gt;&amp;lt;/script&amp;gt;

&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
&amp;lt;button&amp;gt;Hide&amp;lt;/button&amp;gt;
&amp;lt;p&amp;gt;The praragraph to hide when a button is clicked.&amp;lt;/p&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt; 

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Timer functions&lt;/b&gt; like setTimeout(function, delay), setInterval(function, delay), etc will delay the execution of a function. For example, you might want to disable a form button after it's been clicked to prevent double form submission, but then re-enable it again after a few seconds. The clearTimeout() function then allows you to cancel the callback from occuring if some other action is done which means the timeout is no longer required. &lt;br /&gt;
Another reason why these timers are useful is for some repetitive tasks some milliseconds apartment. The reason why the timers are used instead of a simply while (true) { ... } loop is because Javascript is a single-threaded language. So if you tie up the interpreter by executing one piece of code over and over, nothing else in the browser gets a chance to run. So, these timers allow other queued up events or functions to be executed.&lt;br /&gt;
&lt;br /&gt;
Invoke myObj1.myObj1.myMethod() after 1 second. &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var myObj1 = {
     myVar:12, 
  myMethod:function(){
      alert(this.x || "Not defined") ; // "Not defined" is the default if x is not defined
    }
}


setTimeout(function(){myObj1.myMethod()}, 1000);

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Ajax call&lt;/b&gt;s are made asynchronously and when a response is received from the server, a callback method is invoked to process the response. The Ajax calls do have the following states&lt;br /&gt;
&lt;br /&gt;
AJAX states:&lt;br /&gt;
&lt;br /&gt;
0: The request is uninitialized (before you've called open()).&lt;br /&gt;
1: The request is set up, but not sent (before you've called send()).&lt;br /&gt;
2: The request was sent and is in process (you can usually get content headers from the response at this point).&lt;br /&gt;
3: The request is in process; often some partial data is available from the response, but the server isn't finished with its response.&lt;br /&gt;
4: The response is complete; you can get the server's response and use it.&lt;br /&gt;
&lt;br /&gt;
So, you want the callback function to be invoked when the state == 4. Let's look at an example.&lt;br /&gt;
&lt;br /&gt;
Here is the test2.html&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&amp;gt;
&amp;lt;script language="javascript" type="text/javascript" src="ajax.js"&amp;gt;
&amp;lt;/script&amp;gt;

&amp;lt;title&amp;gt;Insert title here&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
The ajax.js.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;function processAjaxRequest(url, callback) {
    var httpRequest; // create our XMLHttpRequest object
    if (window.XMLHttpRequest) {
     //For most browsers
        httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        //For IE
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }

    //onreadystatechange event registers an anonymous (i.e. no name) function
    httpRequest.onreadystatechange = function() {
       // this is called on every state change
       if (httpRequest.readyState === 4) {
            callback.call(httpRequest.responseXML);   // call the callback function
       }
    };
    httpRequest.open('GET', url);
    httpRequest.send();
}


processAjaxRequest ("http://localhost:8000/simple", function() {
    console.log("Executing callaback function....");
    console.log("1.This will be printed when the ajax response is complete. ");   //LINE A
});

console.log("2. This will be printed before the above console.log in LINE A.");   //LINE B

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Note:&lt;/b&gt; If you use FireFox, you can vie the console via Tools --&amp;gt; Web Developer --&amp;gt; Web Console. When you run the above example, check the web console output. &lt;br /&gt;
&lt;br /&gt;
Now, for the purpse of learning JavaScript, Ajax, etc, you can create your own HTTP server with a quick and dirty approach as shown below.  The Java 6, has a built in non-public API for HTTP. This approach should not be used in real life. &lt;br /&gt;
&lt;br /&gt;
The Java HTTP Server&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;



public class SimpleJavaHTTPServer {

 public static void main(String[] args) throws Exception {
  HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
  server.createContext("/simple", new MyHandler());
  server.setExecutor(null); // creates a default executor
  server.start();
 }

 static class MyHandler implements HttpHandler {
  public void handle(HttpExchange t) throws IOException {
   String response = "&amp;lt;ajax-xml&amp;gt;some text&amp;lt;/ajax-xml&amp;gt;";
   t.sendResponseHeaders(200, response.length());
   OutputStream os = t.getResponseBody();
   os.write(response.getBytes());
   os.close();
  }
 }
}

&lt;/pre&gt;&lt;br /&gt;
The LINE B will be printed before LINEA. &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Note:&lt;/b&gt; If you run the above Java code within Java 6 or later, you will get an ajax response of &amp;lt;ajax-xml&amp;gt;some text&amp;lt;/ajax-xml&amp;gt; when you invoke http://localhost:8000/simple. You may get a "restricted API"  in eclipse IDE, you could overcome this by removing and adding the rt.jar via the build path or you could try the following from the preferences menu go into  Java --&amp;gt; Compiler --&amp;gt; Errors/Warnings --&amp;gt; Depricated and Restricted API and change the "forbidden reference" from "Error" to "Warning".&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div style="background-color: white; color: #38761d;"&gt;&lt;span style="font-size: large;"&gt;More JavaScript Q&amp;amp;A&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_10.html"&gt;JavaScript Q&amp;amp;A: Working with the objects&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_8908.html"&gt;JavaScript Interview Q&amp;amp;A: Closure&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and.html"&gt;JavaScript Interview Q&amp;amp;As: Overview&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_26.html" target="_blank"&gt;JavaScript Q&amp;amp;A: Coding&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-4072308294699691202?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/02Tgl-RdxO7wYyaOaLOZDfGeCIE/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/02Tgl-RdxO7wYyaOaLOZDfGeCIE/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/02Tgl-RdxO7wYyaOaLOZDfGeCIE/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/02Tgl-RdxO7wYyaOaLOZDfGeCIE/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/qDVznDAYo2g" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/4072308294699691202/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=4072308294699691202" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/4072308294699691202?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/4072308294699691202?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/qDVznDAYo2g/javascript-interview-questions-and_8681.html" title="JavaScript Interview Questions and Answers: Function.call, Function.apply, and Callback functions" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_8681.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DUMGRX0-fSp7ImA9WhRUFk8.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-7646703260648390300</id><published>2012-01-10T17:13:00.000-08:00</published><updated>2012-01-26T17:23:44.355-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-26T17:23:44.355-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript interview answers" /><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript interview questions" /><title>JavaScript Interview Questions and Answers: Closure</title><content type="html">We earlier saw that JavaScript functions are like objects, and can be passed as arguments from one function to another, can be assigned to a variable, etc.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. What do you understand by the term closure in JavaScript?&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;Whenever you have a function within a function, a closure is used. A closure is like local variables for functions. Let's look at an example.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var calculate = function(x) {     //outer function    
     var myconst = 2; 
     myconst++; //myconst is now 3
     return function(y) {           //inner function
         return x + y + myconst;    // has visibility to parent variable 'myconst'
     }; 
        
}  

//closure 1: each function call has its own closure
var plus5 = calculate(5);       // plus5 is now a closure to the inner function, 
                                // and has access to the outer function's values
                                // when function call exits myconst = 3 and x = 5 

console.log(plus5(3));          // returns 11  i.e. x=5, y=3, myconst=3 


//closure 2: each function call has its own closure
var plus7 = calculate(7);       // plus7 is now a closure to the inner function, 
                                // and has access to the outer function's values
                                // when function call exits const = 3 and x = 7 



console.log(plus7(4));          // returns 14  i.e. x=7, y=4, const=3 


&lt;/pre&gt;&lt;br /&gt;
In general, when you exit out of a function, all the local variables (e.g.myconst and x) go out of scope. As per the above example, you could think that a closure is created on entry to the outer function, and the local variables are added to the closure. The closure is stored to the variable like plus5, plus7, etc and invoked by passing the value for "y". Each function call will have its own closure (e.g. plus5 and plus7)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
So, a closure means the local variables of the outer function is kept alive after the function has returned.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example 2:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;function count() {
    var num = 0;    //local variable that ends up within enclosure
    var display = function() {  // the variable "display" is also part of the closure
       console.log(num++);  
    }
    
    num++; //the num is 1
    
    
    return display;
}


var  increment = count(); // num is 1

increment();    //Can be assigned to a button.
                //every time invoked displays number starting from 2, and incrementing it by 1 as in 2,3,4,etc.

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, the variable "display" is also inside the closure and can be accessed by another function that might be declared inside count() or it could be accessed recursively within the "display" function itself.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. What will be the out put of the following JavaScript when you click on the "click-me" button that invokes the function testList()?&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;form id="evaluate1"&amp;gt;
    &amp;lt;input type="button" value="click-me"  onclick="testList()"/&amp;gt;  
&amp;lt;/form&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;function listCars (list) {
   var listOfFns = [];
   //construct and store functions
   for(var i=0; i&amp;lt;list.length; i++) {
      listOfFns.push(function() {console.log("The car is: "  + list[i])});
   }

   return listOfFns;
}


function testList() {
    var listOfFns = listCars(["Toyota", "Honda", "Ford", "Mazda"]);   //Line A
    //invoke the functions by looping through             
     for(var i=0; i&amp;lt;listOfFns.length; i++) {                          //Line B 
        listOfFns[i]();
     }

}

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;A:&lt;/b&gt; The output will be "The car is: undefined". This is because when the closure is created in "Line A" the the value of the variable "i" in function listCars(…) is 4, which is the exit condition for the for loop. Now in Line B, when you try to execute the inner function&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;function() {
   console.log("The car is: "  + list[i]);
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Since the value of i in the closure is 4, the list only has 4 elements with indices 0,1,2, and 3, the index 4 is undefined. That list[4] is not defined. This is a general gotcha when working with closure and arrays.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Points to remember:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Closures are created every time you create a function in a function.&lt;/li&gt;
&lt;li&gt;Closures give you access to variables that are defined in the parent function, and all of its parents.&lt;/li&gt;
&lt;li&gt;Closures will help you keep your code clean and easy without having to use the global variables.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;//outer function
function createTimer() {
       // inner function invoked from the outer function using closure
       function alertTimerId() {
            // the timerId is a local variable from the outer function, which is in the closure
            alert("The timer id is " + timerId);
       }
     
       //invoke the inner function from the outer.
       var timerId = window.setTimeout(alertTimerId, 1000); // alerts after 1000 ms or 1 second.
}
     
createTimer();

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;setTimeout(code,millisec,lang)
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
code (Required)     -- A reference to the function or the code to be executed&lt;br /&gt;
millisec (Required) -- The number of milliseconds to wait before executing the code&lt;br /&gt;
lang (Optional)     --  The scripting language: JScript | VBScript | JavaScript&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. What is a "module pattern"?&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;The module pattern emulates familiar OO concepts of private and public methods and attributes. It does so by utilizing closures to "hide" elements from the global scope. The public behavior is achieved by returning the private members from your object. Public functions can access the private members.&lt;br /&gt;
&lt;br /&gt;
Global variables are evil, and Douglas Crockford has been teaching a useful singleton pattern for avoiding global variables. The "module pattern" creates an anonymous function, and executes it immediately. All of the code that runs inside the function lives in a closure, which provides privacy and state throughout the lifetime of our application. &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;(function () {
 // all vars and functions are in this scope only
 // still maintains access to all globals
}());

&lt;/pre&gt;&lt;br /&gt;
Note that the () around the anonymous function is required by the language, since statements that begin with the token function are always considered to be function declarations. Including () creates a function expression instead. Here is an example&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var  myProject = {};   //some namespace



myProject.myModule = (function () {



 //"private" variables:

 var myPrivateVar = "myPrivateVar can be accessed only from within myProject.myModule.";



 //"private" method:

 var myPrivateMethod = function () {

  console.log("myPrivateMethod can be accessed only from within myProject.myModule");

 }



 return  {

  myPublicProperty: "myPublicProperty is accessible as myProject.myModule.myPublicProperty.",

  myPublicMethod: function () {

   console.log("myPublicMethod is accessible as myProject.myModule.myPublicMethod.");



   //Within myProject.myModule, I can access "private" vars and methods:

   console.log(myPrivateVar);

   myPrivateMethod();



   //access public members using "this" as the native scope of myPublicMethod is myProject.

   console.log(this.myPublicProperty);

  }

 };



}());





function test() {

    alert(myProject.myModule.myPublicProperty); //defined -- accessing public property

    myProject.myModule.myPublicMethod();        //defined -- accessing public method

    alert(myProject.myModule.myPrivateVar);     //undefined -- accessing private property -- NOT OKAY

    myProject.myModule.myPrivateMethod();       //myProject.myModule.myPrivateMethod is not a function -- accessing private method -- NOT OKAY

}

&lt;/pre&gt;&lt;h6&gt;&lt;a href="http://www.blogger.com/post-edit.g?blogID=35897879&amp;amp;postID=7646703260648390300" name="ModulePattern-ProsandCons"&gt;&lt;/a&gt;&lt;span style="font-size: small;"&gt;Pros and  Cons&lt;/span&gt;&lt;/h6&gt;&lt;b&gt;Pros:&lt;/b&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Easy to pick up for software engineers, as this emulates a familiar pattern  &lt;/li&gt;
&lt;li&gt;Clean encapsulated code  &lt;/li&gt;
&lt;li&gt;Private methods and attributes &lt;/li&gt;
&lt;/ul&gt;&lt;b&gt;Cons:&lt;/b&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Dependent on ordering  &lt;/li&gt;
&lt;li&gt;Accessing public methods requires repeating the parent object name  &lt;/li&gt;
&lt;li&gt;Lack of full support for private members &lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
The Revealing Module Pattern is an extension of the Module Pattern, the main difference being that all methods and attributes are declared as private and optionally exposed in the return of the object. In the process of exposing the methods/attributes we additionally have the option of providing a different name for the exposed reference.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var  myProject = {};        //some namespace

myProject.myObject = (function() {
    var myPrivateVar = "private";
    var myPrivateFunction = function() {
     console.log("private function is called");
        return myPrivateVar;
    }
 
    return {
        publicFunctionName: myPrivateFunction
    }
}())


function test() {
    myProject.myObject.publicFunctionName();       //defined -- accessing public method
    myProject.myObject.myPrivateFunction();        // myProject.myObject.myPrivateFunction is not a function -- NOT OKAY
}


&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Pros and Cons&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Pros:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Easier to read structure &lt;/li&gt;
&lt;li&gt;All methods/attributes are referenced in the same way &lt;/li&gt;
&lt;li&gt;Ability to expose members with a different name &lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;b&gt;Cons:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Lack of full support for private members &lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
You can learn more about the JavaScript design patterns at &lt;a href="http://addyosmani.com/resources/essentialjsdesignpatterns/book/" target="_blank"&gt;Essential JavaScript Design Patterns For Beginners, Volume 1.-- Addy Osmani.&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div style="background-color: white; color: #38761d;"&gt;&lt;span style="font-size: large;"&gt;More JavaScript Q&amp;amp;A&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_10.html"&gt;JavaScript Q&amp;amp;A: Working with the objects&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and.html"&gt;JavaScript Interview Q&amp;amp;A: Overview&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_8681.html"&gt;JavaScript Interview Q&amp;amp;As: Function.call, Function.apply, and Callback functions&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_26.html" target="_blank"&gt;JavaScript Q&amp;amp;A: Coding&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-7646703260648390300?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/Ss3LnN6DtMYnG4GhevUdW_Gvpl8/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Ss3LnN6DtMYnG4GhevUdW_Gvpl8/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/Ss3LnN6DtMYnG4GhevUdW_Gvpl8/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Ss3LnN6DtMYnG4GhevUdW_Gvpl8/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/pSSYl6uDKO8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/7646703260648390300/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=7646703260648390300" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/7646703260648390300?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/7646703260648390300?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/pSSYl6uDKO8/javascript-interview-questions-and_8908.html" title="JavaScript Interview Questions and Answers: Closure" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_8908.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DUQDQnk5fCp7ImA9WhRUFk8.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-5955365602144487131</id><published>2012-01-10T15:43:00.000-08:00</published><updated>2012-01-26T17:22:53.724-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-26T17:22:53.724-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript interview answers" /><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript interview questions" /><title>JavaScript Interview Questions and Answers: Working with the objects</title><content type="html">&lt;b&gt;Q. What are the built-in objects in JavaScript?&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; String, Date, Array, Boolean, and Math.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. What are the different ways to create objects in JavaScript?&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;By invoking the built-in constructor.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var personObj1 = new Object(); // empty object with no properties and methods.
personObj1.name = "John"  ;     //add a property
personObj1.status = "Active";     //add a property
//add a method by associating a function to variable isActive variable.
personObj1.isActive = function() {
     return this.status;
}  

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;By creating a constructor (i.e. a template), and creating an object from the constructor. The Person constructor is like any other function, and it is a convention to start the function name with an uppercase letter to differentiate it with other functions.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;function Person(name, status) {
    this.name = name;
    this.status = status;
    //add a method by associating a function to variable isActive variable.
    personObj1.isActive = function() {
       return this.status;
    }  
   
}

var personObj1 = new Person("John", "Active");


&lt;/pre&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Creating the object as a Hash Literal. This is what used by the JSON, which is a subset of the object literal syntax.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var personObj1 = { };    // empty object

var personObj2 = { 

   name: "John",
   status: "Active",
   isActive: function() {
       return this.status;
   }  
 
}; 

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Q. Does JavaScript has a built-in concept of inheritance?&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; It does to some extent. You can think of every object as inheriting from  it's "prototype". &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. What is a "prototype" property?&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; A prototype is a built-in property of every JavaScript object. For example, &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var personObj1 = new Object();  // empty object with no properties and methods.
personObj1.name = "John"  ;     //add a property
personObj1.status = "Active";   //add a property
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Now, if you create another person object as shown below, all the properties will be empty, and needs to be reassigned.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var personObj2 = new Object();  // empty object with no properties and methods.
personObj2.name = "John"  ;     //add a property
personObj2.status = "Active";   //add a property
&lt;/pre&gt;&lt;br /&gt;
What if you want to set all the Person object status to be "Active" by default without having to explicitly assign it every time? This is where the "prototype" property comes in handy as shown below.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var personObj1 = new Object();            //empty object with no properties and methods.
personObj1.name = "John"  ;               //add a property
personObj1.prototype.status = "Active";   //add a prototype property that will set "Active" as the default


var personObj2 = new Object();  // empty object with status="Active" will be created.
personObj2.name = "John"  ;     // add a property

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When you create an object via a constructor as in var personObj1 = new Person("John", "Active"), the prototype property is also set. When you actually create an object via a constructor, the new operator actually performs the following tasks.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 1: &lt;/b&gt;Creates an empty object as in var personObj1 = new Object();  &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 2:&lt;/b&gt; Attach all properties and methods of the prototype of the function to the resulting object.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 3:&lt;/b&gt; Invoke the function "Person" by passing the new object as the "this" reference.   &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It is important to understand that, all the objects that are created via a constructor function will have the same prototype. This means, if you modify any one object that has been created via the constructor, you will be modifying all the objects that have been created and the new ones you will be creating via the constructor function. You can think of this as every object is inheriting from it's prototype. So, the above approach of individually adding to some properties as in &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;personObj1.prototype.status = "Active";  &lt;/pre&gt;&lt;br /&gt;
can be very handy for methods and constants, and this "prototype" approach is used by many JavaScript frameworks.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. What are some of the best practices relating to coding with JavaScript?&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Use proven frameworks like jQuery, EXT JS, etc to ensure cross browser compatibility, and quality code. &lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Provide a clean separation of content, CSS, and JavaScript. This means store all Javascript code in external script files and build pages that do not rely on Javascript to be usable. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Instead of:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;input id="btn1" type="button" value="click-me1" onclick="test()"/&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Use:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;input id="btn1" type="button" class="something" value="click-me1" /&amp;gt;  
&lt;/pre&gt;&lt;br /&gt;
The above page snippet does not depend on the JavaScript function. The JQuery function below &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;$('input.something').click(function(){
    //do something here
    alert('The button is clicked');
});
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
jQuery allows you to easily attach a click event to the result(s) of your selector. So the code will select all of the &amp;lt;input /&amp;gt; tags of class “something” and attach a click event that will call the function. &lt;br /&gt;
&lt;br /&gt;
Also instead of&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;if(someCondition)
    document.write("write something ........... ");
&lt;/pre&gt;&lt;br /&gt;
Use:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;div title="something"&amp;gt; ... &amp;lt;/div&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var titleElement = $('div[title="something"]');
titleElement.text('Better Approach');
&lt;/pre&gt;&lt;br /&gt;
The above page is renedred as 100% (X)HTML without requiring the JavaScript to write something.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Use code quality tools like JSLint. &lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Use unit testing frameworks like Jasmine, qUnit, etc.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Use "===" instead of "==". If two operands are of the same type and value, then === produces true and !== produces false. If you use "==" or !="" you may run into issues if the operands are of different types.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Avoid using the eval(…) function as it poses a security risk and can also adversely affect performance as it accesses the JavaScript compiler. &lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Namespaces are essential for avoiding type name collisions. JavaScript does not have packages as in Java. But in JavaScript, this can be simulated with empty objects. For example&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var MyPage1 = { };   // empty object acting as a namespace

MyPage1.Person = function(name, status) {
    this.name = name;
    this.status = status;
}

MyPage1.Person.protoyype  = 

{
    isActive: function() {
         return this.status;
    }

}


var personObj1 = new MyPage1.Person("John", "Active");
console.log(personObj1.isActive());

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Simulate encapsulation with Douglas Crawford's approach as shown below as JavaScript does not have access modifiers like private, protected, etc as in Java.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;function Person(name, status) {
      this.get_name = function( ) { return name; }
      this.get_status = function( ) {return status; }
}

Person.prototype.isActive = function( )
{
      return this.get_status();
}


var personObj1 = new Person("John","Active");
console.log(personObj1.isActive( )) ;&lt;/pre&gt;&lt;pre class="brush: csharp"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre class="brush: csharp"&gt;&amp;nbsp;&lt;/pre&gt;&lt;ul&gt;&lt;li&gt;Favor the JavaScript literal way with { … } as opposed to the new Object() to create new objects as the literal way is much more robust and also makes it simpler to code and read.&lt;/li&gt;
&lt;/ul&gt;&lt;pre class="brush: csharp"&gt;&lt;/pre&gt;&lt;ul&gt;&lt;li&gt;Favor [ ]  to declare an array as opposed to an array object with new Array( ). For example,&lt;/li&gt;
&lt;/ul&gt;&lt;pre class="brush: csharp"&gt;var vehicles = ['Car', 'Bus'] ; // creates an array


var vehicles = new Array( ); // creates an array object
vehicles[0] = ''Car" ;
vehicles[1] = 'Bus' ;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Favor using  semicolons (;), and use comma separated variables as opposed to repeating vars. For example&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;//okay
var x = 5;
var y = 6;
var z = 9;

var x =5, y=6,z = 9; // better&lt;/pre&gt;&lt;pre class="brush: csharp"&gt;&amp;nbsp;&lt;/pre&gt;&lt;ul&gt;&lt;li&gt;&lt;pre class="brush: csharp"&gt;Use console.log(...) as oppose to alert(...); for debugging.

&lt;/pre&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div style="background-color: white; color: #38761d;"&gt;&lt;span style="font-size: large;"&gt;More JavaScript Q&amp;amp;A&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_10.html"&gt;JavaScript Q&amp;amp;A: Working with the objects&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_8908.html"&gt;JavaScript Interview Q&amp;amp;A: Closure&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_8681.html"&gt;JavaScript Interview Q&amp;amp;As: Function.call, Function.apply, and Callback functions&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_26.html" target="_blank"&gt;JavaScript Q&amp;amp;A: Coding&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-5955365602144487131?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/UGYXPIVCHxpiTLRCcEGVnjEZmbw/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/UGYXPIVCHxpiTLRCcEGVnjEZmbw/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/UGYXPIVCHxpiTLRCcEGVnjEZmbw/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/UGYXPIVCHxpiTLRCcEGVnjEZmbw/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/bGbFTtv0wfk" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/5955365602144487131/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=5955365602144487131" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/5955365602144487131?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/5955365602144487131?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/bGbFTtv0wfk/javascript-interview-questions-and_10.html" title="JavaScript Interview Questions and Answers: Working with the objects" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_10.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DUYMR3wzfCp7ImA9WhRUFk8.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-9188010176542024446</id><published>2012-01-08T15:14:00.000-08:00</published><updated>2012-01-26T17:19:46.284-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-26T17:19:46.284-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript interview answers" /><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript interview questions" /><title>JavaScript Interview Questions and Answers: Overview</title><content type="html">Like me, many have a love/hate relationship with JavaScript. Now a days, JavaScript is very popular with the rich internet applications (RIA). So, it really pays to know JavaScript. JavaScript is a client side (and server side with node.js) technology that is used to dynamically manipulate the DOM tree. There are a number of JavaScript based frameworks like jQuery available to make your code more cross browser compatible and simpler.&amp;nbsp; Firstly, it is much easier to understand JavaScript if you stop comparing it with Java or understand the key differences. Both are different technologies. &lt;br /&gt;
&lt;br /&gt;
If you need more motivation to learn JavaScript, look at the Node.js, which is a software system designed for writing highly-scalable internet applications in JavaScript, using event-driven, asynchronous I/O to minimize overhead. &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. What is the difference between Java and JavaScript?&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;Don't be fooled by the term &lt;b&gt;Java&lt;/b&gt; in both. Both are quite different technologies. The key differences can be summarized as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;JavaScript variables are dynamically typed, whereas the Java variables are statically typed.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;ul&gt;&lt;pre class="brush: csharp"&gt;var myVar1 = "Hello";&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; //string type
var myVar2 = 5;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; //number type
var myVar3 = new Object( );&amp;nbsp;&amp;nbsp; //empty object type
var myVar4 = {};&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; //empty object type -- JSON (JavaScript Object Notation) style.
&lt;/pre&gt;&lt;/ul&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;In JavaScript properties and methods are dynamically added, whereas Java uses a template called a class.&amp;nbsp; The &lt;i&gt;myVar3&lt;/i&gt; empty object dynamically adds properties and a method.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;ul&gt;&lt;pre class="brush: csharp"&gt;myVar3.firstName = "Test1";  // add a property to object
   myVar3.lastName = "Test2";   // add a property to object
   // add a method
   myVar3.someFunction = function( ) {
           //.…………
   } 
&lt;/pre&gt;&lt;/ul&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;JavaScript function can take variable arguments. You can call the function shown below&amp;nbsp; as myFunction( ), myFunction(20), or myFunction(20,5).&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;ul&gt;&lt;pre class="brush: csharp"&gt;function myFunction( value ) {
   //.…. do something here
}

&lt;/pre&gt;JavaScript has an implicit keyword known as the "arguments",&amp;nbsp; which holds all the passed &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; arguments. It also has a "length" property&amp;nbsp; as in arguments.length to display the number of &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; arguments. Technically an "arguments" is not an array as it does not have the methods like push, pop, or&amp;nbsp; split that an array has. Here is an example.&amp;nbsp;&lt;/ul&gt;&lt;ul&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;   &lt;pre class="brush: csharp"&gt;myFunction(5,10,15,20); 

function myFunction(value) {
   //value is 5;
   //arguments[0] is 5
   //arguments[1] is 10
   //arguments[2] is 15
   //arguments[3] is 20
   //arguments.length is 4
}

&lt;/pre&gt;&lt;/ul&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;JavaScript objects are basically like name/value pairs stored in a &lt;i&gt;HashMap&amp;lt;string,object&amp;gt;&lt;/i&gt;.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
For example, a JavaScript object is represented in JSON style as shown below.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;var personObj = {
         firstName: "John",
         lastName: "Smith",
         age: 25,
         printFullName: function() {
            document.write(this.firstName + "  " +  this.lastName);
         } ,

         printAge: function () {
            document.write("My age is: " +  this.age);
        }    
   }


&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
You can invoke the methods as shown below&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:csharp"&gt;personObj.printFullName();

personObj.printAge();

&lt;/pre&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;JavaScript functions are objects as well. Like objects, the functions can be stored to a variable, passed as arguments, nested within each other, etc. In the above example, nameless functions are attached to variables "printFullName" and "printAge" and invoked via these variables. A function that is attached to an object via a variable is known as a "&lt;b&gt;method&lt;/b&gt;". So, &lt;i&gt;printFullName&lt;/i&gt; and &lt;i&gt;printAge&lt;/i&gt; are methods. &lt;/li&gt;
Technically, what is done with the "add" and "sum" functions is that we have created a new function object and attached them to the variables "add" and sum. As you can see in the example below, the "add" variable is assigned to variable "demo", and the function is invoked via demo(2,5) within the "sum" function.&amp;nbsp;&lt;/ul&gt;&lt;br /&gt;
&lt;ul&gt;&lt;pre class="brush:csharp"&gt;function add(val1, val2) {
    var result = val1 + val2;
    alert("The result is:" + result);
    return result;
}

var demo = add;

function sum() {
   var output = demo(5, 2);
}

&lt;/pre&gt;Now the above temp.js under tutorial/js folder can be invoked from an HTML file under tutorial/html as shown below.     &lt;pre class="brush:csharp"&gt;&amp;lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&amp;gt;

&amp;lt;script language="javascript" type="text/javascript" src="../js/temp.js"&amp;gt;
&amp;lt;/script&amp;gt;

&amp;lt;title&amp;gt;Insert title here&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;form id="evaluate1"&amp;gt;
       &amp;lt;input type="button" value="evaluate"  onclick="sum()"/&amp;gt;   
       &amp;lt;input type="button" value="evaluate2" onclick="demo(3,2)"/&amp;gt;   
       &amp;lt;input type="button" value="evaluate3" onclick="add(2,2)"/&amp;gt;   
    &amp;lt;/form&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/pre&gt;This demonstrates that the functions in JavaScript are objects, and can be passed around. Every function in JavaScript also has a number of attached methods including toString( ), call( ), and apply( ). For example,&amp;nbsp;&amp;nbsp;  The temp2.js is stored under js_tutorial/js.  &lt;pre class="brush: csharp"&gt;function add(val1, val2) {
    var result = val1 + val2;
    alert("Result is:" + result);
    return result;
}


var printAdd = add.toString(); //converts the "add" function to string.

function demo() {   
    alert(printAdd); //alerts the whole source code of the "add" function
}

&lt;/pre&gt;The demo function can be invoked from an html.The temp2.html is stored under js_tutorial/html.&amp;nbsp;&lt;/ul&gt;&lt;pre class="brush: csharp"&gt;&amp;lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&amp;gt;

&amp;lt;script language="javascript" type="text/javascript" src="../js/temp2.js"&amp;gt;
&amp;lt;/script&amp;gt;

&amp;lt;title&amp;gt;Insert title here&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;form id="evaluate1"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;input type="button" value="evaluate"&amp;nbsp; onclick="demo()"/&amp;gt;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/form&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The printAdd cannot be invoked from the HTML because this variable stores the string representation of the source code of the "add"function and not the function itself.&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;JavaScript variables need to be treated like records stored in a HasMap and referenced by name, and not by memory address or pass-by-reference as in Java. The following code snippet demonstrates this.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:csharp"&gt;var x = function () { alert("X"); }
var y = x;
x = function () { alert("Y"); };
y();           // alerts "X" and NOT "Y"
x();           // alerts "Y"
&lt;/pre&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Java does not support closure till atleast version 6. A closure is a &lt;b&gt;function&lt;/b&gt; plus a &lt;b&gt;binding environment&lt;/b&gt;. closures can be passed downwards (as parameters) or returned upwards (as return values). This allows the function to refer to variables of its environment, even if the surrounding code is no longer active. JavaScript supports closure. &lt;br /&gt;
&lt;br /&gt;
In JavaScript a closure is created every time you create a function within a function. When using a closure, you will have access to all the variables in the enclosing (i.e. the parent) function.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:csharp"&gt;var calculate = function(x) {    
     var myconst = 2; 
     return function(y) { 
         return x + y + myconst;    // has visibility to parent variable 'const'
     }; 
}  

var plus5 = calculate(5);         //plus5 is now a closure
alert(plus5(3));                  //returns 10  i.e. x=5, y=3, myconst=2 
alert(plus5(7));                  //returns 14  i.e  x=5, y=7, myconst=2 
alert(plus5(10));                 //returns 17  i.e  x=5, y=10, myconst=2 

&lt;/pre&gt;&lt;/li&gt;
&lt;li&gt;Java programs can be single threaded or multi-threaded. JavaScript engines only have a single thread, forcing events like &lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Asynchronous UI Events like mouse click, focus, etc. It is asynchronous because you don't know when a user is going to click or change a text. &lt;/li&gt;
&lt;li&gt;Timer functions like &lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre class="brush: csharp"&gt;var id = setTimeout(function, delay);    // Initiates a single timer which will call the specified function after the delay. The function returns a unique ID with which the timer can be canceled at a later time. 
var id = setInterval(function, delay);   // Similar to setTimeout but continually calls the function (with a delay every time) until it is canceled. 
clearInterval(id);                       // Accepts a timer ID (returned by either of the aforementioned functions) and stops the timer callback from occurring. 
clearTimeout(id); 
    &lt;/pre&gt;&lt;/li&gt;
&lt;li&gt;Ajax responses asynchronously invoking a callback function when the response is sent back from the server. It is asynchronous because, you don't know how long a server will take to process the ajax request and then to send  the response. &lt;br /&gt;
&lt;br /&gt;
to execute within the same thread. Even though all the above time based events appear to be run concurrently, they are all executed one at a time by queuing all these events. This also mean that if a timer is blocked from immediately executing, it will be delayed until the next possible point of execution making it to wait longer than the desired delay.  This might also cause the intervals execute &lt;br /&gt;
with no delay. &lt;br /&gt;
&lt;br /&gt;
Having said this, HTML5 specifies Web Workers, which is a standardized API for multi-threading JavaScript code. &lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;b&gt;Here are the key points to remember: &lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ol&gt;&lt;li&gt;JavaScript variables are dynamically typed.&lt;/li&gt;
&lt;li&gt;In JavaScript properties and methods are dynamically added.&lt;/li&gt;
&lt;li&gt; JavaScript function can take variable arguments.&lt;/li&gt;
&lt;li&gt;JavaScript objects are basically like name/value pairs stored in a &lt;i&gt;HashMap&amp;lt;string,object&amp;gt;&lt;/i&gt;.&lt;/li&gt;
&lt;li&gt; JavaScript functions are objects as well.&lt;/li&gt;
&lt;/ol&gt;&lt;br /&gt;
&lt;br /&gt;
Here are some working examples:     For the examples shown below, the HTML files are stored under /html sub-folder and JavaScript files are stored under /js sub-folder. The console.log(…) statements are written to your browser's web console. For example, in firefox, you can view the web console via tools  - Web Developer - Web Console. Make sure that the version of Firefox you use has this option. The Web Console is handy for debugging as well.    &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example 1:&lt;/b&gt; two input values are either added or concatenated depending on their types. If both values of type number then add them, otherwise just concatenate the values. Take note of the JavaScript keywords and functions like typeof, isNaN(..), Number(..), parseInt(..), etc. The "document" is part of the DOM tree representing an HTML document in memory. The method "getElementById(...)" will return the relevant "input" element from the DOM tree, and "value" will return the input value that was entered.   &lt;pre class="brush: csharp"&gt;&amp;lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&amp;gt;

&amp;lt;script language="javascript" type="text/javascript" src="../js/evaluate1.js"&amp;gt;
&amp;lt;/script&amp;gt;

&amp;lt;title&amp;gt;Insert title here&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;

    &amp;lt;form id="evaluate1"&amp;gt;
    
     &amp;lt;input id="val1" type="text" value="" /&amp;gt;
     &amp;lt;input id="val2" type="text" value="" /&amp;gt;
     &amp;lt;input type="button" value="evaluate"  onclick="addOrConcat()"/&amp;gt;
     
       
     &amp;lt;p&amp;gt;
     &amp;lt;div id="result"&amp;gt;&amp;lt;/div&amp;gt;
     &amp;lt;/p&amp;gt;
     
    
    &amp;lt;/form&amp;gt;

&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/pre&gt;&lt;pre class="brush: csharp"&gt;function addOrConcat() {
    var val1 = document.getElementById("val1").value;  //string
    var val2 = document.getElementById("val2").value;  //string
    var result = document.getElementById("result");    //object
    
    
    var ans = -1;  //number
    
    //if val1 and val2 are numbers, add them
    if(!isNaN(val1)  &amp;amp;&amp;amp; typeof parseInt(val2) == 'number') {
        ans = Number(val1) + Number(val2);  //add numbers
    }else {
       ans = val1 + val2;                   //string concat
    }
    
    result.innerHTML = "Result is: "  + ans;
    //write to browser console. 
    console.log("val1 is of type " + typeof val1);
    console.log("result is of type " + typeof result);
    console.log("ans is of type " + typeof ans);
}



&lt;/pre&gt;&lt;b&gt;Example 2: &lt;/b&gt;Very similar to Example 1, but uses objects, and passes the relevant values from the call within HTML itself. It also uses the &lt;i&gt;toString( )&lt;/i&gt; method to convert a function object to display its source code.   &lt;pre class="brush: csharp"&gt;&amp;lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&amp;gt;

&amp;lt;script language="javascript" type="text/javascript" src="../js/evaluate3.js"&amp;gt;
&amp;lt;/script&amp;gt;

&amp;lt;title&amp;gt;Insert title here&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;

    &amp;lt;form id="evaluate1"&amp;gt;
    
     &amp;lt;input id="val1" type="text" value="" /&amp;gt;
     &amp;lt;input id="val2" type="text" value="" /&amp;gt;
     &amp;lt;input type="button" value="evaluate"  onclick="addOrConcat(document.getElementById('val1').value,document.getElementById('val2').value)"/&amp;gt;
     
       
     &amp;lt;p&amp;gt;
     &amp;lt;div id="result"&amp;gt;&amp;lt;/div&amp;gt;
     &amp;lt;/p&amp;gt;
     
    
    &amp;lt;/form&amp;gt;

&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/pre&gt;&lt;pre class="brush: csharp"&gt;function addOrConcat(val1,val2) {
 
 var evalObj = new Object(); //create an empty object
 
 evalObj.input1 = val1;     // add a property of type string
 evalObj['input2'] = val2;  // add a property of type string
 evalObj.result = document.getElementById("result"); // add a property of type object
 
 //add a method
 evalObj.evaluate = function() { 
 
      if(!isNaN(this.input1)  &amp;amp;&amp;amp; typeof parseInt(this.input2) == 'number') {
          this.ans = Number(this.input1) + Number(this.input2);  //add numbers
      }else {
          this.ans = evalObj.input1 + this.input2;              //string concat
      }
    
      this.result.innerHTML = "Result is: "  + this.ans;
    
    }
    
    evalObj.evaluate(); //call the method evaluate and "this" refers to evalObj
    console.log(evalObj.evaluate.toString());
   
}


&lt;/pre&gt;&lt;b&gt;Example 3:&lt;/b&gt; Similar to Example 2, with minor modifications to the JavaScript file to demonstrate keywords like "arguments"    &lt;pre class="brush: csharp"&gt;function addOrConcat() {
 
 var evalObj = new Object();                          // create an empty object
 
 evalObj.input1 = arguments[0];                       // this is value1
 evalObj['input2'] = arguments[1];                    // this is value2
 evalObj.result = document.getElementById("result");  // add a property of type object
 
 //add a method
 evalObj.evaluate = function() { 
 
      if(!isNaN(this.input1)  &amp;amp;&amp;amp; typeof parseInt(this.input2) == 'number') {
          this.ans = Number(this.input1) + Number(this.input2);  //add numbers
      }else {
          this.ans = evalObj.input1 + this.input2;              //string concat
      }
    
      this.result.innerHTML = "Result is: "  + this.ans;
    
    }
    
    evalObj.evaluate(); //call the method evaluate and "this" refers to evalObj
    console.log(evalObj.evaluate.toString());
   
}&lt;/pre&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Note: &lt;/b&gt;I am new to JavaScript, so feel free to point out any errors.&lt;br /&gt;
&lt;br /&gt;
&lt;div style="background-color: white; color: #38761d;"&gt;&lt;span style="font-size: large;"&gt;More JavaScript Q&amp;amp;A&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_10.html"&gt;JavaScript Q&amp;amp;A: Working with the objects&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_8908.html"&gt;JavaScript Interview Q&amp;amp;A: Closure&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_8681.html"&gt;JavaScript Interview Q&amp;amp;As: Function.call, Function.apply, and Callback functions&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2012/01/javascript-interview-questions-and_26.html" target="_blank"&gt;JavaScript Q&amp;amp;A: Coding&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-9188010176542024446?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/KA5fh5E9Ek1CPTSbwEo_b122duQ/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/KA5fh5E9Ek1CPTSbwEo_b122duQ/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/KA5fh5E9Ek1CPTSbwEo_b122duQ/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/KA5fh5E9Ek1CPTSbwEo_b122duQ/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/i4ZCNhIWgh0" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/9188010176542024446/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=9188010176542024446" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/9188010176542024446?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/9188010176542024446?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/i4ZCNhIWgh0/javascript-interview-questions-and.html" title="JavaScript Interview Questions and Answers: Overview" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2012/01/javascript-interview-questions-and.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DEcNQ386eSp7ImA9WhRXE0k.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-7930954958073009487</id><published>2011-12-18T23:01:00.000-08:00</published><updated>2011-12-19T17:54:52.111-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-19T17:54:52.111-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="java interview questions" /><title>Tricky Java  interview questions and answers</title><content type="html">&lt;b&gt;Q. &lt;/b&gt;Can interfaces contain inner classes?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt; Yes, but not recommended as it can compromise clarity and security of the code.&lt;br /&gt;
&lt;br /&gt;
The interface with an inner class for demo purpose only&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package innerstatic;

public interface InterfaceWithInnerClass {
    
    
    public static final Util UTIL = new Util( );
    

    public String getName(); // next node in this list

    public final static InterfaceWithInnerClass FIELD =
      //anonymous inner class as the interface field declaration  
      new InterfaceWithInnerClass() {
          public String getName() {
            return "Peter";
        }
    };

    
 //static inner class
    public static class Util {
        public String getDetail(){
            return FIELD.getName() + " age 25";
        }
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The class that implemnts the above interface.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package innerstatic;

public class Test implements InterfaceWithInnerClass {

    @Override
    public String getName() {
        return FIELD.getName() + " : " + UTIL.getDetail();
    }
    
    public static void main(String[] args) {
        System.out.println(new Test().getName());
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The output is:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;Peter : Peter age 25
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; What happens if you pass a primitive int value to a method that accepts&lt;br /&gt;
&lt;br /&gt;
a) long primitive&lt;br /&gt;
b) float primitive&lt;br /&gt;
c) Float object&lt;br /&gt;
d) Number object&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
a) A widening conversion takes place from int to long. So, no compile or run time error.&lt;br /&gt;
b) A widening conversion takes place from int to float. So, no compile or run time error.&lt;br /&gt;
c) compile-time error. primitive type int can be auto-boxed to type Integer, but type Integer and Float are derived from type Number, and don't have the parent child relationship. So, they cannot be implicityly or exlplicitly cast to each other.&lt;br /&gt;
d) primitive type int can be auto-boxed to type Integer, and then implicitly cast to type Number as Number and Integer have the parent child relationship.  So, no compile or run time error.&lt;br /&gt;
&lt;br /&gt;
(More similar type questions are covered with detailed answers in the book "Core Java Career Essentials")&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-7930954958073009487?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/WjBnQqfRURMh9oxRW_4WTKVRSAY/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/WjBnQqfRURMh9oxRW_4WTKVRSAY/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/WjBnQqfRURMh9oxRW_4WTKVRSAY/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/WjBnQqfRURMh9oxRW_4WTKVRSAY/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/rbtA1arFuKA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/7930954958073009487/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=7930954958073009487" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/7930954958073009487?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/7930954958073009487?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/rbtA1arFuKA/tricky-java-interview-questions-and.html" title="Tricky Java  interview questions and answers" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>2</thr:total><feedburner:origLink>http://java-success.blogspot.com/2011/12/tricky-java-interview-questions-and.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CE8MRHY6fyp7ImA9WhRXE0k.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-3109212198557326474</id><published>2011-12-18T22:21:00.001-08:00</published><updated>2011-12-19T17:01:25.817-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-19T17:01:25.817-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="multi-threading interview questions" /><title>More Java multi-threading interview questions and answers?</title><content type="html">&lt;b&gt;Q.&lt;/b&gt; Explain how you would get a Thread Deadlock with a code example?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;The example below causes a deadlock situation by thread1 waiting for lock2 and thread2 waiting for lock1&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package deadlock;

public class DeadlockTest extends Thread {

    public static Object lock1 = new Object();
    public static Object lock2 = new Object();

    public void method1() {
        synchronized (lock1) {
            delay(500);  //some operation
            synchronized (lock2) {
                System.out.println("method1 is executing .... ");
            }
        }
    }

    public void method2() {
        synchronized (lock2) {
            delay(500);   //some operation
            synchronized (lock1) {
                System.out.println("method2 is executing .... ");
            }
        }
    }

    @Override
    public void run() {
        method1();
        method2();
    }

    public static void main(String[] args) {
        DeadlockTest thread1 = new DeadlockTest();
        DeadlockTest thread2 = new DeadlockTest();

        thread1.start();
        thread2.start();
    }

    /**
     * The delay is to simulate some real operation happening.
     * @param timeInMillis
     */
    private void delay(long timeInMillis) {
        try {
            Thread.sleep(timeInMillis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; What happens if you restart a thread that has already started?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;You will get the following exception&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;Exception in thread "main" java.lang.&lt;b&gt;IllegalThreadStateException&lt;/b&gt;
 at java.lang.Thread.start(Thread.java:595)
 at deadlock.DeadlockTest.main(DeadlockTest.java:38)

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; Can you write a program with 2 two threads, in which one prints odd numbers and the other prints even numbers upto 100?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; In Java, you can use wait( ) and notifyAll( ) to communicate between threads. The code below demonstartes that.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Firstly, create the thread classes and the main method that  creates the thread and run it.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package multithreading;

public class NumberGenerator extends Thread {

    private NumberUtility numberUtility;
    private int maxNumber;
    private boolean isEvenNumber;
    

    public NumberGenerator(NumberUtility numberUtility, int maxNumber, boolean isEvenNumber) {
        this.numberUtility = numberUtility;
        this.maxNumber = maxNumber;
        this.isEvenNumber = isEvenNumber;
    }

    public void run() {
        int i = isEvenNumber == true ? 2 : 1;
        while (i &amp;lt;= maxNumber) {
            if(isEvenNumber == true) {
                numberUtility.printEven(i);
            }
            else {
                numberUtility.printOdd(i);    
            }
            
            i = i + 2;
        }
    }
    
    
    public static void main(String[] args) {
        NumberUtility numUtility = new NumberUtility();
        final int MAX_NUM = 100;
        
        NumberGenerator oddGen = new NumberGenerator(numUtility, MAX_NUM, false);
        NumberGenerator evenGen = new NumberGenerator(numUtility, MAX_NUM, true);
        
        oddGen.start();
        evenGen.start();
        
    }

}
&lt;/pre&gt;&lt;br /&gt;
Next, create the utility class that is used for communicating between the two threads with wait() and notifyAll() methods via synchronized methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package multithreading;

import static java.lang.System.out;

public class NumberUtility {

    boolean oddPrinted = false;

    public synchronized void printOdd(int number) {

        while (oddPrinted == true) {
            try {
                wait();   // waits untill notified by even thread

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        out.println("printOdd() " + number);
        oddPrinted = true;
        notifyAll();

    }

    public synchronized void printEven(int number) {
        while (oddPrinted == false) {
            try {
                wait();  //waits until notified by the odd thread

            } catch (InterruptedException e) {

            }
        }

        oddPrinted = false;
        out.println("printEven() " + number);
        notifyAll();
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; Write a multi-threaded Java program in which, one thread generates odd numbers and write to a pipe and the second thread generates even numbers and write to another pipe, and a third thread receives the numbers from both the pipes and evaluates if the sum is multiples of 5?&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; Here is the code snippet.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The Writer threads responsible for writing odd and even numbers to the respective pipes.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package multithreading;

import java.io.IOException;
import java.io.PipedWriter;

public class NumberWriter extends Thread {

    private PipedWriter writer;
    private int maxNumber;
    private boolean isEvenNumber;

    public NumberWriter(PipedWriter writer, int maxNumber, boolean isEvenNumber) {
        this.writer = writer;
        this.maxNumber = maxNumber;
        this.isEvenNumber = isEvenNumber;
    }

    public void run() {
        int i = 1;
        while (i &amp;lt;= maxNumber) {
            try {
                if (isEvenNumber &amp;amp;&amp;amp; (i % 2) == 0) {
                    writer.write(i);
                } else if (!isEvenNumber &amp;amp;&amp;amp; i%2 != 0) {
                    writer.write(i);
                }
                ++i;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        final int MAX_NUM = 100;

        PipedWriter oddNumberWriter = new PipedWriter();
        PipedWriter evenNumberWriter = new PipedWriter();

        NumberWriter oddGen = new NumberWriter(oddNumberWriter, MAX_NUM, false);
        NumberWriter evenGen = new NumberWriter(evenNumberWriter, MAX_NUM, true);
        NumberReceiver receiver = new NumberReceiver(oddNumberWriter, evenNumberWriter);

        oddGen.start();
        evenGen.start();
        receiver.start();

    }

}
&lt;/pre&gt;The receiver thread that listens to both odd and even number pipes and computes the sum. If the sum is a multiple of  5, it prints the numbers and the sum.   &lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package multithreading;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

public class NumberReceiver extends Thread {

    private PipedReader oddReader;
    private PipedReader evenReader;

    public NumberReceiver(PipedWriter oddWriter, PipedWriter evenWriter) {
        try {
            this.oddReader = new PipedReader(oddWriter);
            this.evenReader = new PipedReader(evenWriter);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        int odd =0, even=0;
        
        try {
            while (odd != -1) {
                odd = oddReader.read();
                even = evenReader.read();
                
                if ((odd + even) % 5 == 0) {
                    System.out.println("match found " + odd + " + " + even + " = " + (odd + even));
                }
            }
               
        } catch (IOException e) {
            System.exit(1);
        }
       
        
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style="font-size: large;"&gt;&lt;a href="http://java-success.blogspot.com/2011/09/java-multi-threading-interview.html"&gt;Java multi-threading interview questions and answers: overview &lt;/a&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-3109212198557326474?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/xc1JUT9Wd2QJE7bQx8FJ5ZjB_lo/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/xc1JUT9Wd2QJE7bQx8FJ5ZjB_lo/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/xc1JUT9Wd2QJE7bQx8FJ5ZjB_lo/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/xc1JUT9Wd2QJE7bQx8FJ5ZjB_lo/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/fDAPTKGPVMU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/3109212198557326474/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=3109212198557326474" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/3109212198557326474?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/3109212198557326474?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/fDAPTKGPVMU/more-java-multi-threading-interview.html" title="More Java multi-threading interview questions and answers?" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2011/12/more-java-multi-threading-interview.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CkIDQH47cCp7ImA9WhRQGE4.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-9155505985464932582</id><published>2011-12-13T18:37:00.000-08:00</published><updated>2011-12-13T18:42:51.008-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-13T18:42:51.008-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="JSF Interview Questions" /><category scheme="http://www.blogger.com/atom/ns#" term="JSF" /><category scheme="http://www.blogger.com/atom/ns#" term="JSF Interview Questions and Answers" /><title>JSF Interview Questions and Answers: event handling</title><content type="html">&lt;b&gt;Q.&lt;/b&gt; What are the different types of JSF events?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt;  JSF is an event driven framework.&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;b&gt;Action Events:&lt;/b&gt; bound to UI Command objects like a Command Button or a Hyper-link. Whenever a user presses a Command Button or clicks a hyperlink these Events get generated.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Value Change Events&lt;/b&gt;: bound to UI Components like Text Field, Check-Box, List and Radio Buttons. The Value Change Event is fired as soon as the value that is displayed in the view is modified. &lt;/li&gt;
&lt;li&gt;&lt;b&gt;Phase Events&lt;/b&gt;: As you saw earlier in the JSF overview blog, the request processing life-cycle in JSF includes six phases and any JSF implementation will fire Phase events during the start and end of each phase. If we want to capture the Phase Events, then can define a Phase Listener. These are handy for debugging as well.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How are events handled in JSF? What is the difference between these event handling mechanisms?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; &lt;b&gt;Action handlers &lt;/b&gt;and &lt;b&gt;event listeners&lt;/b&gt; provide an event driven mechanism. Every time a user does something like clicking a button, selecting an item from a drop down, or submitting a form, an event occurs. Event notification is then sent via HTTP to the server and handled by the FacesServlet. Events can invoke custom business logic or initiate page navigation.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
JSF provides two types of methods for handling events; listeners and action handlers, both of these may be defined within a managed bean. A listener takes an FacesEvent as a parameter and a void return type, while an action handler takes no parameters and returns a String. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example 1:&lt;/b&gt; An event handler &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;!-- login.xhtml--&amp;gt;
&amp;lt;h:inputText id="useName" /&amp;gt;
&amp;lt;h:inputSecret id="password" /&amp;gt;
&amp;lt;h:commandButton action="#{login.submit}"&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;!-- faces-config.xml--&amp;gt;
&amp;lt;navigation-rule&amp;gt;
     &amp;lt;from-view-id&amp;gt;/login.xhtml&amp;lt;/from-view-id&amp;gt;
  &amp;lt;navigation-case&amp;gt;
     &amp;lt;from-action&amp;gt;#{login.submit}&amp;lt;/from-action&amp;gt;
  &amp;lt;from-outcome&amp;gt;success&amp;lt;/from-outcome&amp;gt;
  &amp;lt;to-view-id&amp;gt;&amp;lt;/to-view-id&amp;gt;
  &amp;lt;/navigation-case&amp;gt;    
&amp;lt;/navigation-rule
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;//Login managed bean
public String submit(  ) {
      //do some action
       ....

       return "success"  //navigate to /home.jsf     
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example 2: &lt;/b&gt;An &lt;b&gt;event handler&lt;/b&gt; with an &lt;b&gt;event listener&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Action listeners are provided by JSF to make it easier to handle action events.  An advantage of using a listener is that the FacesEvent object provides additional information, such as the form element that initiated the event. An action handler in contrast has no knowledge of the source of the event, but based upon its return value, can initiate page navigation. The example below shows using both event handlers and event listeners.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;h:commandButton value="Search" actionListener="#{orders.confirm}" action="#{orders.search}" /&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
In the above example, when the button is clicked the JSF implementation calls the action listener during the Invoke Application phase. The action listener method then has a chance to perform any processing related to the command element selected by the user. You can perform any processing you need to inside the method. The method can have any name, must be public, return void, and accept an ActionEvent as its only parameter.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;public void confirm(ActionEvent event) {
       int calculatedAge = calculateAgeFromDOB();
       if (event.getComponent().getId().equals("confirm")) {
            //perform some action
   ....
       }
    
    else if(event.getComponent().getId().equals("validate")){
         //perform some other action
   ....
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
After the action listener method is called, the method bound by the action attribute will be called, and the JSF implementation will determine where to navigate next.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;public String search( ) {
    //some action logic
 ...
 //navigation logic
 return "success";
}
&lt;/pre&gt;&lt;br /&gt;
Since the action listener method is called before the action handler method, the action listener method can modify the response that the action method returns. &lt;br /&gt;
&lt;br /&gt;
An action listener can also be implemented as shown below.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;h:commandButton id="submitOrderSearch" value="Search" action="#{orders.search}" &amp;gt;
     &amp;lt;f:actionListener type="com.MyAppActionListenerImpl" /&amp;gt;
&amp;lt;/h:commandButton&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
The listener class can be implemented as shown below:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com;

...

public class MyAppActionListenerImpl implements ActionListener {

    public void processAction(ActionEvent aev) {
      System.out.println(aev.getId());
   ...
   }

}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
A ValueChangeEvent is useful whenever you want to be notified when there is a change in the value of a component, such as text modification in a text field or a check box selection. Most JSF components support the valueChangeListener attribute. &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;h:inputText  id="orderStatus"  valueChangeListener="#{orders.onStatusChange}" /&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
The managed bean method:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;public void onStatusChange(ValueChangeEvent vce) {
     System.out.println(vce.getId());
  System.out.println(vce.getOldValue());
  System.out.println(vce.getNewValue());
  ....
}
&lt;/pre&gt;&lt;br /&gt;
This can also be implemented as shown below.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;h:inputText  id="orderStatus" &amp;gt;
    &amp;lt;f:valueChangeListener type="com.MyAppValueChangeActionListenerImpl" /&amp;gt;
&amp;lt;/h:imputText&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
The managed bean method:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com;

...

public class MyAppValueChangeActionListenerImpl implements ValueChangeListener {

    public void processValueChange(ValueChangeEvent vce) {
      System.out.println(vce.getId());
   System.out.println(vce.getOldValue());
      System.out.println(vce.getNewValue());
      ....
   }

}&amp;nbsp;&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div style="color: #741b47;"&gt;&lt;span style="font-size: large;"&gt;More JSF Interview Questions and Answers&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt; &lt;a href="http://java-success.blogspot.com/2011/12/jsf-interview-questions-and-answers_09.html"&gt;JSF Interview Questions and Answers: postback and viewstate&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2011/10/jsf-interview-questions-and-answers.html"&gt;JSF Interview Questions and Answers: Overview&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-9155505985464932582?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/gyD-q6Sen3UHwGuLFTFx0hjekNY/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/gyD-q6Sen3UHwGuLFTFx0hjekNY/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/gyD-q6Sen3UHwGuLFTFx0hjekNY/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/gyD-q6Sen3UHwGuLFTFx0hjekNY/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/8vpIPcx2fO8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/9155505985464932582/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=9155505985464932582" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/9155505985464932582?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/9155505985464932582?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/8vpIPcx2fO8/jsf-interview-questions-and-answers_13.html" title="JSF Interview Questions and Answers: event handling" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2011/12/jsf-interview-questions-and-answers_13.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CkQCSXYzfCp7ImA9WhRQGE4.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-4222244792884758076</id><published>2011-12-09T16:39:00.000-08:00</published><updated>2011-12-13T18:39:28.884-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-13T18:39:28.884-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="JSF Interview Questions" /><category scheme="http://www.blogger.com/atom/ns#" term="JSF Interview Questions and Answers" /><title>JSF Interview Questions and Answers: postback and viewstate</title><content type="html">&lt;b&gt;Q.&lt;/b&gt; What is the difference between initial request and postback?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt;  Initial request (e.g. HTTP GET)  is the request that is made from a browser in order to display a page. Postback happens when the browser posts the page back to the server with form values, etc. Initial request is created by clicking a link, pasting an URL in address bar, while a postback request is create by posting a form by clicking a submit button or any post request.  Initial request passes only restore View &amp;amp; Render Response phases, while postback request process under all phases described in the  JSF life cycle diagram. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
During the restore view phase of the life cycle, ViewHandler retrieves the ResponseStateManager object in order to test if the request is a postback or an initial request. If a request is a postback, the restoreView method of ViewHandler is called. This method uses the ResponseStateManager object to re-build the component tree and restore state. &lt;br /&gt;
The ResponseStateManager object is the only one that knows what rendering technology is being used and is therefore the only one that can look at a request, which is rendering-technology specifiec. Here are the basic steps.&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;An isPostBack method on ResponseStateManager returns true if the current request is a postback.&lt;/li&gt;
&lt;li&gt;A getState method is called by the restoreView method of ViewHandler to retrieve the component tree state from the current request.  &lt;/li&gt;
&lt;li&gt;A writeState method that writes out the state to the client.  This method is called by the renderView method of ViewHandler during the render response phase. &lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;b&gt;Q. &lt;/b&gt;What is a viewstate in JSF?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; In JSF, there is a viewstate associated with each page, which is passed back and forth with each submits. The reason for the viewtate is that the HTTP is a stateless protocol.  The state of the components across requests need to be maintained. The viewstate can change in between requests as new controls like UIInput can be added or modified. The view state is divided into two parts. &lt;br /&gt;
&lt;br /&gt;
Part 1: Structure of the components&lt;br /&gt;
Part 2: Defines the state of the components. For example. enabled/disabled, input values, checked/unchecked, selected item, etc.&lt;br /&gt;
&lt;br /&gt;
Understanding the JSF lifecycle helps understand the viewstate.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-bC8QIZcP5Zs/TuKqFu4_QkI/AAAAAAAAAR8/oRgEtTDXohc/s1600/jsf-lifecycle-viewstate.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="640" src="http://1.bp.blogspot.com/-bC8QIZcP5Zs/TuKqFu4_QkI/AAAAAAAAAR8/oRgEtTDXohc/s640/jsf-lifecycle-viewstate.JPG" width="454" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
It can be achieved by either storing the viewstate on the server side in a session and then passing the viewstate id to the client via a hidden field as shown below:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Server side&lt;/b&gt;: In web.xml file, set the state saving strategy&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;context-param&amp;gt;
     &amp;lt;param-name&amp;gt;javax.faces.STATE_SAVING_METHOD&amp;lt;/param-name&amp;gt;
     &amp;lt;param-value&amp;gt;server&amp;lt;/param-value&amp;gt;
&amp;lt;/context-param&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
The hidden field passed to the client&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="cdx43wedsfdg654ed" /&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Client side&lt;/b&gt;: serializing the view state on the client. Do the following in web.xml&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;context-param&amp;gt;
     &amp;lt;param-name&amp;gt;javax.faces.STATE_SAVING_METHOD&amp;lt;/param-name&amp;gt;
     &amp;lt;param-value&amp;gt;client&amp;lt;/param-value&amp;gt;
&amp;lt;/context-param&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div style="color: #741b47;"&gt;&lt;span style="font-size: medium;"&gt;More JSF Interview Questions and Answers&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt; &lt;a href="http://java-success.blogspot.com/2011/10/jsf-interview-questions-and-answers.html"&gt;JSF Interview Questions and Answers: overview&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2011/12/jsf-interview-questions-and-answers.html"&gt;JSF Interview Questions and Answers: Seam&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2011/12/jsf-interview-questions-and-answers_13.html"&gt;JSF Interview Questions and Answers: events handling&lt;/a&gt;&amp;nbsp; &lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-4222244792884758076?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/UNZxpyzfoI_1DrJUOXapVklIxeo/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/UNZxpyzfoI_1DrJUOXapVklIxeo/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/UNZxpyzfoI_1DrJUOXapVklIxeo/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/UNZxpyzfoI_1DrJUOXapVklIxeo/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/vvniqHG2cBo" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/4222244792884758076/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=4222244792884758076" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/4222244792884758076?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/4222244792884758076?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/vvniqHG2cBo/jsf-interview-questions-and-answers_09.html" title="JSF Interview Questions and Answers: postback and viewstate" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://1.bp.blogspot.com/-bC8QIZcP5Zs/TuKqFu4_QkI/AAAAAAAAAR8/oRgEtTDXohc/s72-c/jsf-lifecycle-viewstate.JPG" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2011/12/jsf-interview-questions-and-answers_09.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CkMER3o-fSp7ImA9WhRQGE4.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-5440860720677465780</id><published>2011-12-08T20:13:00.000-08:00</published><updated>2011-12-13T18:40:06.455-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-13T18:40:06.455-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="JSF Interview Questions" /><category scheme="http://www.blogger.com/atom/ns#" term="JSF" /><category scheme="http://www.blogger.com/atom/ns#" term="Seam interview questions" /><category scheme="http://www.blogger.com/atom/ns#" term="Seam" /><title>JSF Interview Questions and Answers: Seam</title><content type="html">&lt;b&gt;Q.&lt;/b&gt; How does Seam framework fit in with the JSF framework?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;JSF's major shortcoming is its heavy reliance on the HTTP session, especially when propagating data across a sequence of pages. Seam rectifies this with a conversational scope. Seam provides some hooks into the JSF life cycle to achieve this along with other benefits.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-O1vNTTqZG5Q/TuGKtBUblFI/AAAAAAAAAR0/p9PeS0M0NQk/s1600/jsf-seam-lifecycle.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="640" src="http://4.bp.blogspot.com/-O1vNTTqZG5Q/TuGKtBUblFI/AAAAAAAAAR0/p9PeS0M0NQk/s640/jsf-seam-lifecycle.JPG" width="590" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div style="color: #741b47;"&gt;&lt;span style="font-size: medium;"&gt;More JSF Interview Questions and Answers&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt; &lt;a href="http://java-success.blogspot.com/2011/12/jsf-interview-questions-and-answers_09.html"&gt;JSF Interview Questions and Answers: postback and viewstate&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2011/10/jsf-interview-questions-and-answers.html"&gt;JSF Interview Questions and Answers: Overview&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2011/12/jsf-interview-questions-and-answers_13.html"&gt;JSF Interview Questions and Answers: events handling&lt;/a&gt;&amp;nbsp;&amp;nbsp; &lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-5440860720677465780?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/qXqwHm79bkWYVp1glx4H_4WfJZE/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/qXqwHm79bkWYVp1glx4H_4WfJZE/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/qXqwHm79bkWYVp1glx4H_4WfJZE/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/qXqwHm79bkWYVp1glx4H_4WfJZE/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/mZ6SPzaKcng" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/5440860720677465780/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=5440860720677465780" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/5440860720677465780?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/5440860720677465780?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/mZ6SPzaKcng/jsf-interview-questions-and-answers.html" title="JSF Interview Questions and Answers: Seam" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://4.bp.blogspot.com/-O1vNTTqZG5Q/TuGKtBUblFI/AAAAAAAAAR0/p9PeS0M0NQk/s72-c/jsf-seam-lifecycle.JPG" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2011/12/jsf-interview-questions-and-answers.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DEAGQHwzfCp7ImA9WhRQE0U.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-3794878430893274426</id><published>2011-12-07T22:53:00.000-08:00</published><updated>2011-12-08T15:25:21.284-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-08T15:25:21.284-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="design patterns interview questions" /><category scheme="http://www.blogger.com/atom/ns#" term="design patterns" /><title>Design patterns interview Questions and answers: observer pattern</title><content type="html">The design patterns are very popular with the interviewers and Java/J2EE Job Interview Companion covers GoF design patterns, J2EEE design patterns, and EJB design patterns. This blog entry covers the observer design pattern.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; What is an observer design pattern?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; The Observer pattern is a behavioral design pattern that&amp;nbsp; allows an object (an Observer) to watch another object (a Subject). The subject and observer to have a publish/subscribe relationship. Observers can register to receive events from the Subject. &lt;br /&gt;
&lt;br /&gt;
Some of the practical uses of observer pattern are:&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;When a change to one object requires changing of others, and you don't know how many objects need to be changed.&lt;/li&gt;
&lt;li&gt;When an object should be able to notify other objects without making assumptions about who these objects are and not tightly coupling them.&lt;/li&gt;
&lt;li&gt;When a report is received or an event occurs, a message needs to be sent to the subscribed handlers.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;b&gt;Examples:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Programming Swing based GUI applications where the listeners register them with events like button click, property change, etc.&lt;/li&gt;
&lt;li&gt;Programming a stock market application to know when the price of a stock changes.&lt;/li&gt;
&lt;li&gt;Programming a order placement or trading application to know the status changes like pending, filled, shipped, rejected, etc.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
So, whenever you want to have the state change or other information, instead of polling every few second, register the observers with a subject.&amp;nbsp; &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-C8ug1ilF6Tc/TuBey65_MXI/AAAAAAAAARk/BY27z2nQqFc/s1600/design-pattern-observer.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="266" src="http://3.bp.blogspot.com/-C8ug1ilF6Tc/TuBey65_MXI/AAAAAAAAARk/BY27z2nQqFc/s640/design-pattern-observer.JPG" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is some pseudo code of this third scenario&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 1:&lt;/b&gt; Define the Subject and Observer interfaces&lt;br /&gt;
&lt;br /&gt;
This is the subject interface&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com;

public interface ReportExecutor {
    public void addHandler(ReportHandler rh);
    public void removeHandler(ReportHandler rh);
    public void processReport(String message);
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
This is the observer interface&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com;

public interface ReportHandler {
    //handles report
    public void handleMessage(String message);
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 2:&lt;/b&gt; Define the concrete subject and observers.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The concrete subject&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com;

import java.util.ArrayList;
import java.util.List;

public class SalesReportExecutor implements ReportExecutor {
    
    //list of observers that register their interest in SalesReport
    private List&lt;reporthandler&gt; reportHandlers = new ArrayList&lt;reporthandler&gt;();

    @Override
    public void addHandler(ReportHandler rh) {
        reportHandlers.add(rh);
    }

    @Override
    public void processReport(String message) {
        for (ReportHandler reportHandler : reportHandlers) {
            reportHandler.handleMessage(message);
        }
    }

    @Override
    public void removeHandler(ReportHandler rh) {
        reportHandlers.remove(rh);

    }

}
&lt;/reporthandler&gt;&lt;/reporthandler&gt;&lt;/pre&gt;&lt;br /&gt;
The concrete observers&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com;

public class LoggingReportHandler implements ReportHandler {

    @Override
    public void handleMessage(String message) {
        //handles report by formatting and printing
        System.out.println("Logging report  " + message);
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com;

public class EmailReportHandler implements ReportHandler {

    @Override
    public void handleMessage(String message) {
        //handles the report by formatting it differently and emailing.
        System.out.println("Emailing report " + message);
        //logic to email report.
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 3: &lt;/b&gt;Finally, the JMS listener class that uses the  subject. The JMS Listener class listens on a queue for presence of a report.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.mgl.mts.fix;

import javax.jms.Message;
import javax.jms.TextMessage;

public class MyAppListener {

    public void onMessage(Message message) {
        if (message instanceof TextMessage) {

            ReportExecutor executor = new SalesReportExecutor();
            executor.addHandler(new LoggingReportHandler());
            executor.addHandler(new EmailReportHandler());
            executor.processReport(message.toString());

        } else {
            throw new IllegalArgumentException("Message must be of type TextMessage");
        }
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Q. &lt;/b&gt;Can you list some Java interfaces that use the observer design pattern?&lt;br /&gt;
&lt;b&gt;A&lt;/b&gt;. &lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;The Java Message Service (JMS) models the observer pattern, with its guaranteed delivery, non-local distribution, and persistence, to name a few of its benefits. The JMS publish-subscribe messaging model allows any number of subscribers to listen to topics of interest. When a message for the published topic is produced, all the associated subscribers are notified.&lt;/li&gt;
&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;The Java Foundation Classes (JFC) like JList, JTree and the JTable components manipulate data through their respective data models. The components act as observers of their data models.&lt;/li&gt;
&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;In the &lt;i&gt;java.util &lt;/i&gt;package, we have the &lt;b&gt;Observer &lt;/b&gt;interface and the &lt;b&gt;Observable &lt;/b&gt;class.&lt;/li&gt;
&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;In an &lt;b&gt;MVC &lt;/b&gt;(Model-View-Controller) architecture, the view gets its own data from the model or in some cases the controller may issue a general instruction to the view to render itself. In others, the view acts as an observer&amp;nbsp; and is automatically notified by the model of changes in state that require a screen update. &lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; What are the pros and cons of an Observer design pattern?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;PROS:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Loose coupling between Subject and Observer: The subject knows only a list of observers, that implement the Observer interface, it does no know the concrete implementation of the Observer. &lt;/li&gt;
&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;Broadcast communication: An event notification is broadcast to observers irrespective of the number of Observers&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;b&gt;CONS:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;If not used carefully the observer pattern can add unnecessary complexity.&lt;/li&gt;
&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;The order of Observer notifications is undependable. Simply registering the observers in a particular order will not enforce their order of notification. You don't necessarily know if the first registered listener is notified first or last. If you need to have cascading notifications, where object X must be notified first, followed by object Y, you must introduce an intermediary object to enforce the ordering.&amp;nbsp; &lt;/li&gt;
&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;The possibility of a memory leak. A reference to the Observer is maintained by the Subject. Until the Subject releases the reference, the Observer cannot be removed by the garbage collector.&lt;br /&gt;
&lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-3794878430893274426?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/5BFo8Q5H3hSNY54MoZU7PTU2Zd0/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/5BFo8Q5H3hSNY54MoZU7PTU2Zd0/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/5BFo8Q5H3hSNY54MoZU7PTU2Zd0/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/5BFo8Q5H3hSNY54MoZU7PTU2Zd0/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/-wfL-OtzDNg" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/3794878430893274426/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=3794878430893274426" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/3794878430893274426?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/3794878430893274426?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/-wfL-OtzDNg/design-patterns-interview-questions-and.html" title="Design patterns interview Questions and answers: observer pattern" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://3.bp.blogspot.com/-C8ug1ilF6Tc/TuBey65_MXI/AAAAAAAAARk/BY27z2nQqFc/s72-c/design-pattern-observer.JPG" height="72" width="72" /><thr:total>1</thr:total><feedburner:origLink>http://java-success.blogspot.com/2011/12/design-patterns-interview-questions-and.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CkEBQXk4fip7ImA9WhRQE0w.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-5658078128410074962</id><published>2011-12-05T18:19:00.000-08:00</published><updated>2011-12-07T18:17:30.736-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-07T18:17:30.736-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Spring Interview Questions and Answers" /><category scheme="http://www.blogger.com/atom/ns#" term="Spring interview questions" /><category scheme="http://www.blogger.com/atom/ns#" term="Spring interview answers" /><title>Spring Interview Questions and Answers: JNDI, JMS, other</title><content type="html">&lt;b&gt;Q.&lt;/b&gt; How can you configure JNDI in spring application context?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;Using "org.springframework.jndi.JndiObjectFactoryBean". For example, &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example 1:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"   scope="singleton"&amp;gt;
  &amp;lt;property name="jndiName"&amp;gt;
   &amp;lt;value&amp;gt;java:comp/env/jdbc/dataSource/myapp_ds&amp;lt;/value&amp;gt;
  &amp;lt;/property&amp;gt;
 &amp;lt;/bean&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Example 2:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&amp;gt;
&amp;lt;property name="locations" value="classpath:myapp.properties" /&amp;gt;
&amp;lt;property name="ignoreUnresolvablePlaceholders" value="true" /&amp;gt;
&amp;lt;/bean&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
The myapp.properties &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;jndi.naming.myapp=java:comp/env/jdbc/dataSource/myapp_ds
...
&lt;/pre&gt;&lt;br /&gt;
Use the property "jndi.naming.myapp"&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;bean id="mfsShyDS" class="org.springframework.jndi.JndiObjectFactoryBean"&amp;gt;
&amp;lt;property name="jndiName"&amp;gt;
&amp;lt;value&amp;gt;${jndi.naming.myapp}&amp;lt;/value&amp;gt;
&amp;lt;/property&amp;gt;
&amp;lt;/bean&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; What is difference between singleton and prototype bean?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; If you had noticed the above examples, the scope was set to "singleton". This means single bean instance per IOC container. n Spring, bean scope is used to decide which type of bean instance should be return from Spring container back to the caller.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Scopes:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;b&gt;singleton &lt;/b&gt;– Return a single bean instance per Spring IoC container&lt;/li&gt;
&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;b&gt;prototype &lt;/b&gt;– Return a new bean instance each time when requested&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
the default scope is &lt;b&gt;singleton&lt;/b&gt;. The web-aware scopes are&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;request – Return a single bean instance per HTTP request. &lt;/li&gt;
&lt;li&gt;session – Return a single bean instance per HTTP session. &lt;/li&gt;
&lt;li&gt;globalSession – Return a single bean instance per global HTTP session.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How would you use Spring to send JMS based messages&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; Here is some pseudocode that uses Spring with JNDI and JMS to send messages. It assumes that the ConnectionFactory and Destination values are configured via JNDI.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;To send messages&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Locate a ConnectionFactory, typically using JNDI.&lt;/li&gt;
&lt;li&gt;Locate a Destination, typically using JNDI.&lt;/li&gt;
&lt;li&gt;Create a Spring JmsTemplate with the ConnectionFactory.&lt;/li&gt;
&lt;li&gt;Create a  JmsTemplate using the  ConnectionFactory.&lt;/li&gt;
&lt;li&gt;Inject the JmsTemplate and the destination to your "MyAppMessageSender" to send messages using the jmsTemplate and the destination you just injected.&lt;/li&gt;
&lt;li&gt;A sessiion needs to be created via the Spring class MessageCreator, and subsequently a message is created on the session created.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;b&gt;To receive messages&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Locate a ConnectionFactory, typically using JNDI.&lt;/li&gt;
&lt;li&gt;Locate a Destination, typically using JNDI.&lt;/li&gt;
&lt;li&gt;Create a message listener class (e.g. com.MyAppListener)&lt;/li&gt;
&lt;li&gt;Create a JMS message container by injecting ConnectionFactory, Destination, and the listener. The container is responsible for binding the listener to the queue.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt; 
&amp;lt;beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd 
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd"&amp;gt; 

 &amp;lt;!-- JNDI configuration --&amp;gt;
    &amp;lt;bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate"&amp;gt; 
        &amp;lt;property name="environment"&amp;gt; 
            &amp;lt;props&amp;gt; 
                &amp;lt;prop key="java.naming.factory.initial"&amp;gt;org.jnp.interfaces.NamingContextFactory&amp;lt;/prop&amp;gt; 
                &amp;lt;prop key="java.naming.provider.url"&amp;gt;jnp://localhost:1099&amp;lt;/prop&amp;gt; 
                &amp;lt;prop key="java.naming.factory.url.pkgs"&amp;gt;org.jboss.naming:org.jnp.interfaces&amp;lt;/prop&amp;gt; 
                &amp;lt;prop key="java.naming.security.principal"&amp;gt;admin&amp;lt;/prop&amp;gt; 
                &amp;lt;prop key="java.naming.security.credentials"&amp;gt;admin&amp;lt;/prop&amp;gt; 
            &amp;lt;/props&amp;gt; 
        &amp;lt;/property&amp;gt; 
    &amp;lt;/bean&amp;gt;  
  
  
    &amp;lt;bean id="jmsConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean"&amp;gt; 
        &amp;lt;property name="jndiTemplate" ref="jndiTemplate" /&amp;gt; 
        &amp;lt;property name="jndiName" value="MyAppConnectionFactory" /&amp;gt; 
    &amp;lt;/bean&amp;gt; 
 
  &amp;lt;bean id="jmsQueueDestination" class="org.springframework.jndi.JndiObjectFactoryBean"&amp;gt; 
        &amp;lt;property name="jndiTemplate" ref="jndiTemplate" /&amp;gt; 
        &amp;lt;property name="jndiName"&amp;gt; 
            &amp;lt;value&amp;gt;queue/MyAppQueue&amp;lt;/value&amp;gt; 
        &amp;lt;/property&amp;gt; 
    &amp;lt;/bean&amp;gt; 
 
 &amp;lt;bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"&amp;gt;
           &amp;lt;property name="connectionFactory" ref="jmsConnectionFactory"/&amp;gt;
 &amp;lt;/bean&amp;gt;
 
 
 &amp;lt;bean id="sender" class="com.MyAppMessageSender"&amp;gt; 
         &amp;lt;property name="connectionFactory" ref="connectionFactory"/&amp;gt;
   &amp;lt;property name="queue" ref="jmsQueueDestination"&amp;gt; 
     
    &amp;lt;/bean&amp;gt;


 &amp;lt;!-- POJO Messgae Listener --&amp;gt;
 &amp;lt;bean id="jmsMessageListener" class="com.MyAppListener" /&amp;gt;
  
   
   &amp;lt;!-- Connects the queue to the POJO message listener --&amp;gt;
    &amp;lt;bean id="jmsContainer"  class="org.springframework.jms.listener.DefaultMessageListenerContainer"&amp;gt; 
        &amp;lt;property name="connectionFactory" ref="jmsConnectionFactory" /&amp;gt; 
        &amp;lt;property name="destination" ref="jmsQueueDestination" /&amp;gt; 
        &amp;lt;property name="messageListener" ref="jmsMessageListener" /&amp;gt; 
    &amp;lt;/bean&amp;gt; 

  
&amp;lt;/beans&amp;gt; 
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Here is the message sender -- com.MyAppMessageSender&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;


public class MyAppMessageSender {
    
    private JmsTemplate jmsTemplate; 
    private Destination destination; 

   
    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    public void setDestination(Destination destination) {
        this.destination = destination;
    } 
    
    
    public void sendMessage() { 
        this.jmsTemplate.send(this.destination, new MessageCreator() { 
            public Message createMessage(Session session) throws JMSException { 
              return session.createTextMessage("message from myapp"); 
            } 
        }); 
    } 
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Here is the message receiver -- com.MyAppListener. The onMessage(...) method in invoked asynchronously when a message apper in the destination (e.g. Queue/Topic)&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

public class MyAppListener implements MessageListener {
    public void onMessage(Message message) {
        if (message instanceof TextMessage) {
            try {
                System.out.println(((TextMessage) message).getText());
            }
            catch (JMSException ex) {
                throw new RuntimeException(ex);
            }
        }
        else {
            throw new IllegalArgumentException("Message must be of type TextMessage");
        }
    }
}
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-5658078128410074962?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/v3lMzrnCckoZQ4xhPE89SMQLLeo/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/v3lMzrnCckoZQ4xhPE89SMQLLeo/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/v3lMzrnCckoZQ4xhPE89SMQLLeo/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/v3lMzrnCckoZQ4xhPE89SMQLLeo/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/ZS4zvn8Sisw" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/5658078128410074962/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=5658078128410074962" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/5658078128410074962?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/5658078128410074962?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/ZS4zvn8Sisw/spring-interview-questions-and-answers.html" title="Spring Interview Questions and Answers: JNDI, JMS, other" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2011/12/spring-interview-questions-and-answers.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DUUMSXk6eSp7ImA9WhRQF0s.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-8808340962300309707</id><published>2011-12-04T21:40:00.000-08:00</published><updated>2011-12-13T01:08:08.711-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-13T01:08:08.711-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Hibernate interview answers" /><category scheme="http://www.blogger.com/atom/ns#" term="HIbernate Interview Questions" /><category scheme="http://www.blogger.com/atom/ns#" term="Hibernate interview questions and answers" /><title>Hibernate Interview questions and answers:  cacheing</title><content type="html">&lt;b&gt;Q.&lt;/b&gt; What is a second-level cache in Hibernate?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the &lt;i&gt;SessionFactory &lt;/i&gt;object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. The second-level cache needs to be explicitly configured. Hibernate provides a flexible concept to exchange cache providers for the second-level cache. By default Ehcache is used as caching provider. However more sophisticated caching implementation can be used like the distributed JBoss Cache or Oracle Coherence.&lt;br /&gt;
&lt;br /&gt;
The Hibernate configuration looks like:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;property name="hibernate.cache.use_second_level_cache"&amp;gt;true&amp;lt;/property&amp;gt;
&amp;lt;property name="hibernate.cache.provider_class"&amp;gt;org.hibernate.cache.EhCacheProvider&amp;lt;/property&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
The ehcache.xml can be configured to cache objects of type com.myapp.Order as shown below&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;cache name="com.myapp.Order"
   maxElementsInMemory="300"
   eternal="true"
   overflowToDisk="false"
   timeToIdleSeconds="300"
   timeToLiveSeconds="300"
   diskPersistent="false"
   diskExpiryThreadIntervalSeconds="120"
   memoryStoreEvictionPolicy="LRU"       
/&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
second-level cache reduces the database traffic by caching loaded objects at the SessionFactory level between transactions. These objects are available to the whole application, not just to the user running the query. The 'second-level' cache exists as long as the session factory is alive. The second-level cache holds on to the 'data' for all properties and associations (and collections if requested) for individual entities that are marked to be cached. It is imperative to implement proper cache expiring strategies as caches are never aware of changes made to the persistent store by another application. he following are the list of possible cache strategies. &lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;b&gt;Read-only&lt;/b&gt;: This is useful for data that is read frequently, but never updated. This is the most simplest and best-performing cache strategy.&lt;/li&gt;
&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;b&gt;Read/write&lt;/b&gt;: Read/write caches may be appropriate if your data needs to be updated. This carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when session.close() or session.disconnect() is called.&lt;br /&gt;
&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Nonstrict read/write&lt;/b&gt;: This is most appropriate for data that is read often but only occasionally modified.This strategy does not guarantee that two transactions won't simultaneously modify the same data. &lt;br /&gt;
&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Transactional&lt;/b&gt;: This is a fully transactional cache that may be used only in a JTA environment.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
It can be enabled via the Hibernate  mapping files as shown below:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;class name="com.myapp.Order"&amp;gt;

    &amp;lt;cache usage="read-write"/&amp;gt;
    ....
&amp;lt;/class&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
Note: The usage options are: transactional|read-write|nonstrict-read-write|read-only. The cache can also be enabled at different granular level (e.g. parent, children, etc). The active orders will be cached  for 300 seconds. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How does the hibernate second-level cache work?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; Hibernate always tries to first retrieve objects from the session and if this fails it tries to retrieve them from the second-level cache. If this fails again, the objects are directly loaded from the database.  Hibernate's static initialize() method, which populates a proxy object, will attempt to hit the second-level cache before going to the database. The Hibernate class provides static methods for manipulation of proxies. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;public final class Hibernate extends Object {
    ....
 public static void initialize(Object proxy)  throws HibernateException 
    .... 
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
As a consequence of using the Hibernate second-level cache, you have to be aware of the fact that each call of a data access method can either result in a cache hit or miss. So, configure your log4j.xml to log your hits and misses.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;logger name="org.hibernate.cache"&amp;gt;
   &amp;lt;level value="DEBUG" /&amp;gt;
&amp;lt;/logger&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
Alternatively, you can use Spring AOP to log the cache access on your DAO methods. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The second level cache is a powerful mechanism for improving performance and scalability of your database driven application. Read-only caches are easy to handle, while read-write caches are more subtle in their behavior. Especially, the interaction with the Hibernate session can lead to unwanted behavior.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. &lt;/b&gt;What is a query cache in Hibernate?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; The query cache is responsible for caching the results and to be more precise the keys of the objects returned by queries.  Let us have a look how Hibernate uses the query cache to retrieve objects. In order to make use of the query cache we have to modify the person loading example as follows.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;Query query = session.createQuery("from Order as o where o.status=?");
query.setInt(0, "Active");
query.setCacheable(true); // the query is cacheable
List l = query.list();
&lt;/pre&gt;&lt;br /&gt;
You also have to change the hibernate configuration to enable the query cache. This is done by adding the following line to the Hibernate configuration.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;property name="hibernate.cache.use_query_cache"&amp;gt;true&amp;lt;/property&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; What ar ethe pitfalls of second level and query caches?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; Memeory is a finite resource, and over use or incorrect useage like cacheing the Order object and all its referenced objects can cause OutOfMemoryError. Here are some tips to overcome the pitfalls relating to cacheing.&lt;br /&gt;
&lt;br /&gt;
1. Set entity’s keys as query parameters, rather than setting the entire entity object. Critreia representations should also use identifiers as parameters. Write HQL queries to use identifiers in any substitutable parameters such as WHERE clause, IN clause etc.For example&lt;br /&gt;
&lt;br /&gt;
In the example below, the entire customer and everything he/she references would be held in cache until either the query cache exceeds its configured limits and it is evicted, or the table is modified and the results become dirty.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;final Customer customer = ... ;
final String hql = "FROM Order as order WHERE order.custOrder = ?"
final Query q = session.createQuery(hql);
q.setParameter(0, customer);
q.setCacheable(true);
&lt;/pre&gt;&lt;br /&gt;
Instead of setting the whole customer object as shown above, just set the id. &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;final Order customer = ... ;
final String hql = "from Order as order where order.cusomer.id = ?"
final Query q = session.createQuery(hql);
q.setParameter(0, customer.getId());
q.setCacheable(true);
&lt;/pre&gt;&lt;br /&gt;
2. Hibernate's query cache implementation is pluggable by decorating Hibernate's query cache implementation. This involves overriding the put() method to check if a canonical equivalent of a query results object already exist in the Object[][], and assign the same QueryKey if it exists. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3. If you are in a single JVM using in memory cache only, use hibernate.cache.use_structured_entries=false in your hibernate configuration. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are some general performance tips:&lt;br /&gt;
&lt;br /&gt;
1. Session.load will always try to use the cache. Session.find does not use the cache for the primary object, but cause the cache to be populated. Session.iterate always uses the cache for the primary object and any associated objects.&lt;br /&gt;
&lt;br /&gt;
2. While developing, enable the show SQL and monitor the generated SQL. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;property name="show_sql"&amp;gt;true&amp;lt;/property&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Also enable the "org.hibernate.cache" logger in your log4j.xml to monitor cache hits and misses.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color: #a64d79; font-size: medium;"&gt;More Hibernate Related Interview Questions and Answers&lt;/span&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2010/12/hibernate-interview-questions-q.html"&gt;Hibernate Interview Questions and Answers:overview&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2011/11/spring-interview-questions-and-answers_30.html"&gt;Hibernate Interview Questions and Answers:Spring integration&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-8808340962300309707?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/9qH_l0ktyr8uYeRrS63WKuW6RV4/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/9qH_l0ktyr8uYeRrS63WKuW6RV4/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/9qH_l0ktyr8uYeRrS63WKuW6RV4/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/9qH_l0ktyr8uYeRrS63WKuW6RV4/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/Tsp2uTGf0Ao" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/8808340962300309707/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=8808340962300309707" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/8808340962300309707?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/8808340962300309707?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/Tsp2uTGf0Ao/hibernate-interview-questions-and.html" title="Hibernate Interview questions and answers:  cacheing" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2011/12/hibernate-interview-questions-and.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0QHQ30zfyp7ImA9WhRQEEk.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-8533369268434379850</id><published>2011-11-30T21:03:00.000-08:00</published><updated>2011-12-04T15:28:52.387-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-04T15:28:52.387-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Hibernate interview answers" /><category scheme="http://www.blogger.com/atom/ns#" term="Spring interview questions" /><title>Spring Interview Questions and Answers: Hibernate integration</title><content type="html">&lt;b&gt;Q. &lt;/b&gt;How would you integrate Hibernate with Spring?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;The hibernate can be wired up via Spring as shown below.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 1: &lt;/b&gt;The Hibernate properties.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp; &amp;lt;!--&amp;nbsp; hibernate properties--&amp;gt;
&amp;nbsp;&amp;nbsp; &amp;lt;bean id="myappHibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;property name="properties"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;props&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;prop key="hibernate.dialect"&amp;gt;org.hibernate.dialect.SybaseDialect&amp;lt;/prop&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;prop key="hibernate.show_sql"&amp;gt;false&amp;lt;/prop&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;prop key="hibernate.cache.provider_class"&amp;gt;net.sf.ehcache.hibernate.SingletonEhCacheProvider&amp;lt;/prop&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/props&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/property&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/bean&amp;gt;&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 2:&lt;/b&gt; The DataSource.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;lt;!-- datasource configured via JNDI--&amp;gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp; &amp;lt;bean id="myappDataSource" class="org.springframework.jndi.JndiObjectFactoryBean"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;property name="jndiName"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;value&amp;gt;java:comp/env/jdbc/dataSource/myapp-ds&amp;lt;/value&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/property&amp;gt;
&amp;nbsp; &amp;lt;/bean&amp;gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&lt;/pre&gt;&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&lt;b&gt;&amp;nbsp;STEP 3:&lt;/b&gt; The hibernate mapping files. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;
&amp;nbsp;&amp;nbsp; &amp;lt;bean name="myappHibernateMappingFiles" class="org.springframework.beans.factory.config.ListFactoryBean"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;property name="sourceList"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;list&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;value&amp;gt;hbm/Order.hbm.xml&amp;lt;/value&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;value&amp;gt;hbm/Trade.hbm.xml&amp;lt;/value&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;value&amp;gt;hbm/Customer.hbm.xml&amp;lt;/value&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/list&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/property&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/bean&amp;gt;
&lt;/pre&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;
&lt;b&gt;STEP 4:&lt;/b&gt; An empty interceptor&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;!-- An interceptor that does nothing. May be used as a base class for application-defined custom interceptors. --&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;bean id="myappEntityInterceptor" class="org.hibernate.EmptyInterceptor" /&amp;gt;
&lt;/pre&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;
&lt;b&gt;STEP 5:&lt;/b&gt; Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory. &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;!-- Define the session factory --&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;bean name="myappSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" autowire="byName"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;property name="hibernateProperties"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;ref bean="myappHibernateProperties"/&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/property&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;property name="dataSource"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;ref bean="myappDataSource"/&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/property&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;property name="mappingResources"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;ref bean="myappHibernateMappingFiles"/&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/property&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;property name="entityInterceptor"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;ref bean="myappEntityInterceptor"/&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/property&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/bean&amp;gt;
&lt;/pre&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 6:&lt;/b&gt; The hibernate template. Helper class that simplifies Hibernate data access code. &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;!-- Hibernate Template --&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;bean name="myappHibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" autowire="no" scope="prototype"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;property name="sessionFactory"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;ref bean="myappSessionFactory"/&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/property&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;property name="allowCreate"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;value&amp;gt;false&amp;lt;/value&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/property&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;property name="maxResults"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;value&amp;gt;50000&amp;lt;/value&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/property&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;property name="flushMode"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;value&amp;gt;3&amp;lt;/value&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/property&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/bean&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;
&lt;b&gt;STEP 7:&lt;/b&gt; The repository class for data access logic.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;!-- Constructor Inject the Template into your Repository classes&amp;nbsp; (Data acess layer)&amp;nbsp; --&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;lt;bean id="myappOrderRepository" class="com.HibernateOrderRepository"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;constructor-arg&amp;gt;&amp;lt;ref bean="myappHibernateTemplate" /&amp;gt;&amp;lt;/constructor-arg&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/bean&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;
&lt;b&gt;STEP 8:&lt;/b&gt; The service class that uses one or more repositories. &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;lt;!-- Service Layer: myappOrderRepository is injected via setter injection&amp;nbsp; --&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;lt;bean id="myappOrderService" class="com.OrderServiceImpl"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp; &amp;lt;property&amp;gt;&amp;lt;ref bean="myappOrderRepository" /&amp;gt;&amp;lt;/property&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/bean&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;&amp;nbsp;STEP 9:&lt;/b&gt; The repository interface and class that makes use if the hibernate template.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
package com;

import com.ObjectNotFoundException;

public interface OrderRepository {
&amp;nbsp;&amp;nbsp;&amp;nbsp; public Order load(Long identity) throws ObjectNotFoundException;
&amp;nbsp;&amp;nbsp;&amp;nbsp; public void save(Order order);
}&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The template.load, template.save, etc are database operations via the HibernateTemplate.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
package com;

import org.apache.log4j.Logger;
import org.springframework.orm.hibernate3.HibernateObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.ObjectNotFoundException;
import com.Order;
import com.OrderRepository;


public class HibernateOrderRepository implements OrderRepository {
&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; private static final Logger LOG = Logger.getLogger(HibernateOrderRepository.class);

&amp;nbsp;&amp;nbsp;&amp;nbsp; private final HibernateTemplate template;
&amp;nbsp; 

&amp;nbsp;&amp;nbsp;&amp;nbsp; public HibernateOrderRepository(HibernateTemplate template) {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.template = template;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }

&amp;nbsp;&amp;nbsp;&amp;nbsp; @Override
&amp;nbsp;&amp;nbsp;&amp;nbsp; /**
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; * Read Order from database
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; */
&amp;nbsp;&amp;nbsp;&amp;nbsp; public Order load(Long identity) throws ObjectNotFoundException {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (LOG.isDebugEnabled()) {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; LOG.debug("Loading " + identity);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; try {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return template.load(Order.class,identity);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; } catch (HibernateObjectRetrievalFailureException e) {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; throw new ObjectNotFoundException(identity + " not found", e);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; } 
&amp;nbsp;&amp;nbsp;&amp;nbsp; }

&amp;nbsp;&amp;nbsp;&amp;nbsp; /**
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; * Save the record to database
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; * @param order&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; */
&amp;nbsp;&amp;nbsp;&amp;nbsp; public void save(Order order) {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (LOG.isDebugEnabled()) {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; LOG.debug("Saving " + order);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; template.save(order);
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q:&lt;/b&gt; How do you wire up a transaction manager?&lt;br /&gt;
&lt;b&gt;A: &lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 1:&lt;/b&gt; Define a transaction manager.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;!-- Transaction Manger --&amp;gt;
 &amp;lt;bean name="myappTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&amp;gt;
        &amp;lt;property name="sessionFactory" ref="myappSessionFactory" /&amp;gt;
    &amp;lt;/bean&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 2: &lt;/b&gt;Create a transaction interceptor that uses the above transaction manager.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;bean id="myappHibernateInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"&amp;gt;
        &amp;lt;property name="transactionManager" ref="myappTransactionManager" /&amp;gt;
        &amp;lt;property name="transactionAttributes"&amp;gt;
            &amp;lt;props&amp;gt;
                &amp;lt;prop key="*"&amp;gt;PROPAGATION_REQUIRED,-Exception&amp;lt;/prop&amp;gt;
            &amp;lt;/props&amp;gt;
        &amp;lt;/property&amp;gt;
    &amp;lt;/bean&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 3: &lt;/b&gt;Create other optional interceptors for logging, deadlock retry, etc.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;!-- SERVICE INTERCEPTORS --&amp;gt;
    
    &amp;lt;bean id="myappLoggingInterceptor" class="com.MyAppLoggingInterceptor" /&amp;gt;
    &amp;lt;bean id="myappDeadlockRetryInterceptor" class="com.OracleDeadlockRetryInterceptor" /&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;STEP 4:&lt;/b&gt; Wire up the interceptors to an abstract  service&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;!-- SERVICES --&amp;gt;
    
    &amp;lt;bean id="myappAbstractService" abstract="true" class="org.springframework.aop.framework.ProxyFactoryBean"&amp;gt;
        &amp;lt;property name="interceptorNames"&amp;gt;
            &amp;lt;list&amp;gt;
                &amp;lt;value&amp;gt;myappLoggingInterceptor&amp;lt;/value&amp;gt;
                &amp;lt;value&amp;gt;myappDeadlockRetryInterceptor&amp;lt;/value&amp;gt;
                &amp;lt;value&amp;gt;myappHibernateInterceptor&amp;lt;/value&amp;gt;
            &amp;lt;/list&amp;gt;
        &amp;lt;/property&amp;gt;
    &amp;lt;/bean&amp;gt;
 &lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 5: &lt;/b&gt;The concrete service that uses the myappOrderRepository along with the interceptors. Especially the "myappHibernateInterceptor" that performs transaction demarcation.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;bean id="myappOrderService" parent="myappAbstractService"&amp;gt;
     &amp;lt;property name="proxyInterfaces"&amp;gt;
            &amp;lt;value&amp;gt;com.mgl.mts.oms.model.service.OrderService&amp;lt;/value&amp;gt;
        &amp;lt;/property&amp;gt;
        &amp;lt;property name="target"&amp;gt;
            &amp;lt;bean class="com.OrderServiceImpl"&amp;gt;
             &amp;lt;constructor-arg&amp;gt;&amp;lt;ref bean="myappOrderRepository" /&amp;gt;&amp;lt;/constructor-arg&amp;gt;
            &amp;lt;/bean&amp;gt;
        &amp;lt;/property&amp;gt;
    &amp;lt;/bean&amp;gt;&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 6&lt;/b&gt; The OrderServiceImpl class looks like&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com;

import ....

public class OrderServiceImpl implements OrderService {

    private final Logger LOG = Logger.getLogger(OrderServiceImpl.class);

    private final OrderRepository orderRepository;

    public OrderServiceImpl(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }
    
    //......  
}

&lt;/pre&gt;&lt;b&gt;Note&lt;/b&gt;: The &lt;i&gt;OrderServiceImpl &lt;/i&gt;will have the interceptors turned using AOP to manage transaction, logging, and deadlock retry. The diagram below gives a big picture of interceptors, service, and repository.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-6GnYotczYBc/Ttg5qMljijI/AAAAAAAAARc/yHUk0oiL5Wg/s1600/spring-interceptors.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="640" src="http://4.bp.blogspot.com/-6GnYotczYBc/Ttg5qMljijI/AAAAAAAAARc/yHUk0oiL5Wg/s640/spring-interceptors.JPG" width="306" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;b&gt;Note:&lt;/b&gt; The deadlock retry filter is an interesting one. When an exception is thrown, it is inspected using a pattern matching (i.e. regular expression)&amp;nbsp; to see if it is due to deadlock. If it is due to deadlock the invocation is repeated. This makes the call again to the target, which is the &lt;i&gt;OrderServiceimpl &lt;/i&gt;via the &lt;i&gt;TransactionInterceptor&lt;/i&gt;, which starts a new transaction.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is an example of the custom interceptor  -- myappLoggingInterceptor. Aspect-Oriented Programming (AOP) offers a better solution to many problems. he AOP Alliance project (aopalliance-x.x.jar)  is a joint open-source project between several software engineering people who are interested in AOP and Java. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.test;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;


public class MyAppLoggingInterceptor implements MethodInterceptor {
    
    private static final Logger LOG = Logger.getLogger(MyAppLoggingInterceptor.class);

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        long begin = System.currentTimeMillis();
        
        //proceed to the next interceptor on the chain 
        Object result = invocation.proceed();
        
        long end = System.currentTimeMillis();;
        
        LOG.info("Time elapsed " + (end - begin) + " ms");
        
        return result;
    }

}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
The deadlock retry interceptor&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.test;

import java.sql.SQLException;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;


public class OracleDeadlockRetryInterceptor implements MethodInterceptor {
    
    private static final Logger LOG = Logger.getLogger(OracleDeadlockRetryInterceptor.class);
    
    private int attempts = 3;

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        return doInvoke(invocation, 1);
    }

    private Object doInvoke(MethodInvocation invocation, int count) throws Throwable {
        try {
            //proceed to next interceptor
            return invocation.proceed();
        } catch (Exception exception) {
            if (!isDeadlockException(exception)) {
                throw exception;
            }
            LOG.warn("A Database deadlock occured. Will try again.", exception);
            if (count &amp;lt; attempts) {
                count++;
                return doInvoke(invocation, count);
            }
            throw new SQLException("Service Invocation failed " + attempts
                        + " times with a SQLException.", exception);
        }
    }

}&amp;nbsp;&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;&lt;span style="color: #a64d79; font-size: large;"&gt;More Spring Interview Questions and Answers&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2011/11/spring-interview-questions-and-answers.html"&gt;Spring Interview Questions and Answers : Spring Bean life cycle, DI, and IOC&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.html"&gt;Spring Interview Questions and Answers: Overview&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2011/11/spring-interview-questions-and-answers_29.html"&gt;Spring Interview Questions and Answers: read properties file       &lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-8533369268434379850?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/udU6zD9gSexmwQIanqpiUvy0rX8/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/udU6zD9gSexmwQIanqpiUvy0rX8/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/udU6zD9gSexmwQIanqpiUvy0rX8/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/udU6zD9gSexmwQIanqpiUvy0rX8/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/qEcTS8l4lTU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/8533369268434379850/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=8533369268434379850" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/8533369268434379850?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/8533369268434379850?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/qEcTS8l4lTU/spring-interview-questions-and-answers_30.html" title="Spring Interview Questions and Answers: Hibernate integration" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://4.bp.blogspot.com/-6GnYotczYBc/Ttg5qMljijI/AAAAAAAAARc/yHUk0oiL5Wg/s72-c/spring-interceptors.JPG" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2011/11/spring-interview-questions-and-answers_30.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DE8HR3k9fyp7ImA9WhRQF0s.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-5949620943422443407</id><published>2011-11-30T04:51:00.000-08:00</published><updated>2011-12-13T01:00:36.767-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-13T01:00:36.767-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="feeling stagnated" /><category scheme="http://www.blogger.com/atom/ns#" term="changing jobs" /><title>Are you feeling stagnated?</title><content type="html">One of the dilemmas many professionals face is &lt;b&gt;when to jump the ship? &lt;/b&gt;versus &lt;b&gt;when to steady the ship?&lt;/b&gt; There is no right or wrong answer to this question, and the answer depends on the individual circumstances. But here are some of my thoughts that might aid in your decision making. With the start of a new year, you may be among the millions of people thinking of making an important change in your life.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div style="color: #741b47;"&gt;&lt;span style="font-size: large;"&gt;"Thanks and farewell" emails &lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
From time to time, I receive goodbye&amp;nbsp; emails, and in fact a recent email similar to the one below prompted me to write this blog entry.&lt;br /&gt;
&lt;br /&gt;
Hello all,&lt;br /&gt;
&lt;br /&gt;
After nearly 5 and a half years working for XYZ, it has been decided that my role will no longer be required beyond 2nd December 2011. &lt;br /&gt;
....&lt;br /&gt;
Thanks for the good times and ...............&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In this scenario, it is fine if you had acquired marketable and sought-after skills to move on with your career, and not fine if your skills and knowledge were not kept up to date. Even if you find your work boring or not challenging, there is no excuse for not motivating yourself to acquire sought-after skills as there are plethora of online tutorials/articles and good books to keep your knowledge up to date. But, in a longer term, it is always better to acquire the much needed hands-on commercial experience. The skills to watch out for include technical skills, soft skills, domain knowledge, and personal traits. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div style="color: #741b47;"&gt;&lt;span style="font-size: large;"&gt;Work at XYZ until you get a gold watch? &lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
There are no more jobs like that – companies are under too much pressure to be lean and flexible (layoffs, downsizing, reorganization), so workers have to be, too (take on new challenges, acquire new skills). People jump the ship for a number of reasons like life style changes, feeling bored, burnt or stressed out, feeling stagnated, and wanting to earn more money. People steady the ship for a number of reasons like already jumped the ship too often, not ready to take on new challenges due to personal reasons, bad economy, etc. About 30 years ago, when my parents were in their working years, the prevailing notion was that an employer would "take care of you" for a long time with a secure job and a decent pension. But that's gone the way of the typewriter and carbon paper. Today, it's not uncommon to change jobs voluntarily every few years. Changing jobs (obviously, not too often) will &lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;enhance your experience and broaden your knowledge and skills&lt;/li&gt;
&lt;li&gt;help you build up a wider network&lt;/li&gt;
&lt;li&gt;make you progress in your career a lot quicker.&lt;/li&gt;
&lt;li&gt;give the confidence to find a job whenever you need to&lt;/li&gt;
&lt;li&gt;increase your earning potential. If you  are lucky enough to get a promotion with your current company, they  will only give you a small increase in salary, just enough to justify  the promotion and keep you.  If you however require a  decent promotion and increased package, changing jobs and employer is the way to go.&amp;nbsp; &lt;/li&gt;
&lt;/ul&gt;In fact, stability is a big goal for new workers today because the old path of staying at the same job for stability does not necessarily work for everyone. &lt;b&gt;Note&lt;/b&gt;: Some do progress well within the same organization. Here are a few tell tale signs to jump the ship when the time is right.&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Your skills are not respected. If you feel that your employer doesn’t  recognize your value to the company, then it may be time for a change. When you hand in your resignation, you are asked questions like -- what can I do to keep you here? &lt;/li&gt;
&lt;li&gt;You’re stuck in the same position, doing the same  things, for nearly the same pay, for a long time, it’s time to shake  things up. Be realistic of the situation, rather than deluding yourselves into  believing that things will miraculously improve or what your boss tell  you to convince you to stay back. &lt;/li&gt;
&lt;li&gt;Constantly looking at your watch and being unhappy at work.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div style="color: #741b47;"&gt;&lt;span style="font-size: large;"&gt;Balance is the key&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
You need a balance between "changing ships too often" and "not changing ships at all". Some employers in selected industry segments will wonder "what's wrong" with an individual who has not changed jobs in X years, and on the other hand, there are still many employers who will look on frequent changes unfavorably. The obvious implications for them are, that you won't stay long enough to make any significant contributions, and that if you were hired, perhaps your tendency to leave quickly will inspire many otherwise loyal employees to leave as well.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color: #741b47; font-size: large;"&gt;How do you go about steadying the ship? &lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
So, if you jump the ship too often, it is imperative that you find a way to communicate your frequent changes in the past as a positive, not a negative in your resume and at job interviews. For example, &lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Change in career direction.&lt;/li&gt;
&lt;li&gt;Emphasizing that one of your primary objectives in this job change is to find an employer that will provide challenges and growth opportunities over the years.&lt;/li&gt;
&lt;li&gt;Emphasizing that stability and permanence are at the top of your list of priorities, and that the targeted company appears to be one .&lt;/li&gt;
&lt;li&gt;Providing references to your past employers who will vouch positively for your capabilities. This is why it is vital to always move on in good terms. Never burn bridges. Networking is a key aspect in your career progression.&lt;/li&gt;
&lt;li&gt;Focusing more on your past accomplishments in your resume and at job interviews.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;div style="color: #674ea7;"&gt;&lt;span style="font-size: large;"&gt;Conclusion&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;
You are the captain of your ship, and best placed to solve your dilemma based on your current circumstance and career aspirations. It is not an easy decision to make. What ever your decision is, &lt;b&gt;don't base it on monetary value alone &lt;/b&gt;and &lt;b&gt;continuously learn&lt;/b&gt;.&amp;nbsp; Use a multi-attribute decision model like the one discussed in blog entry -- &lt;a href="http://java-success.blogspot.com/2007/10/how-to-choose-from-multiple-javaj2ee.html"&gt;How to choose from multiple job offers?&lt;/a&gt; to cover all angles. &lt;br /&gt;
&lt;ul&gt;&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-5949620943422443407?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/meaUYpAHO8OZJ8oLd9yMEH4s6fc/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/meaUYpAHO8OZJ8oLd9yMEH4s6fc/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/meaUYpAHO8OZJ8oLd9yMEH4s6fc/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/meaUYpAHO8OZJ8oLd9yMEH4s6fc/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/OduJ-YQv9Wg" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/5949620943422443407/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=5949620943422443407" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/5949620943422443407?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/5949620943422443407?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/OduJ-YQv9Wg/are-you-feeling-stagnated.html" title="Are you feeling stagnated?" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2011/11/are-you-feeling-stagnated.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DUUBQHw4fSp7ImA9WhRRF0Q.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-2012877019825103384</id><published>2011-11-29T21:14:00.000-08:00</published><updated>2011-12-01T19:40:51.235-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-01T19:40:51.235-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Spring Interview Questions and Answers" /><category scheme="http://www.blogger.com/atom/ns#" term="Spring interview questions" /><category scheme="http://www.blogger.com/atom/ns#" term="Spring" /><title>Spring Interview Questions and Answers: read properties file</title><content type="html">&lt;b&gt;Q.&lt;/b&gt; How do you read properties file in spring?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; PropertyPlaceholderConfigurer allows you to share a properties files. You can simply share one properties file for all of your build info or you can separate things out, and have multiple properties files in your build script.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Managing properties for an enterprise application can be a bit trickier than one might expect. The following link covers some basics around working with properties files.&lt;br /&gt;
&lt;br /&gt;
&lt;a href="http://java-success.blogspot.com/2011/11/java-interview-questions-and-answers.html"&gt;Working with properties files&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 1:&lt;/b&gt; Prepare the properties file to use.  The myapp.properties file contains name/value pairs as shwon below.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;#statuses
order.status.rejected=REJECTED
order.status.filled=FILLED
order.status.shipped=SHIPPED
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;STEP 2: &lt;/b&gt;Define the interface and the implementation classes that read these properties.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

public interface OrderNotification {
    abstract void processOrder();
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The statuses are read from the above properties file.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

import java.util.Map;

public class OrderNotificationImpl implements OrderNotification {

//read from properties file
private Map&lt;string,string&gt; statuses;

public OrderNotificationImpl(Map&lt;string,string&gt; statuses) {
this.statuses = statuses;
}

@Override
public void processOrder() {
//....
System.out.println(statuses.get("REJECTED"));
}
}

&lt;/string,string&gt;&lt;/string,string&gt;&lt;/pre&gt;&lt;b&gt;STEP 3:&lt;/b&gt; The beans3.xml that read properties file and inject relevant values. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:jee="http://www.springframework.org/schema/jee"
 xsi:schemaLocation="
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"&amp;gt;


 &amp;lt;bean id="propertyPlaceholderConfigurer"
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&amp;gt;
  &amp;lt;property name="locations"&amp;gt;
   &amp;lt;list&amp;gt;
    &amp;lt;value&amp;gt;classpath:test/myapp.properties&amp;lt;/value&amp;gt;
   &amp;lt;/list&amp;gt;
  &amp;lt;/property&amp;gt;
 &amp;lt;/bean&amp;gt;


 &amp;lt;!-- inject properties --&amp;gt;
 &amp;lt;bean id="orderStatus" class="java.util.LinkedHashMap"&amp;gt;
  &amp;lt;constructor-arg&amp;gt;
   &amp;lt;map key-type="java.lang.String" value-type="java.lang.String"&amp;gt;
    &amp;lt;entry key="REJECTED"&amp;gt;
     &amp;lt;value&amp;gt;${order.status.rejected}&amp;lt;/value&amp;gt;
    &amp;lt;/entry&amp;gt;
    &amp;lt;entry key="FILLED"&amp;gt;
     &amp;lt;value&amp;gt;${order.status.filled}&amp;lt;/value&amp;gt;
    &amp;lt;/entry&amp;gt;
    &amp;lt;entry key="SHIPPED"&amp;gt;
     &amp;lt;value&amp;gt;${order.status.shipped}&amp;lt;/value&amp;gt;
    &amp;lt;/entry&amp;gt;
   &amp;lt;/map&amp;gt;
  &amp;lt;/constructor-arg&amp;gt;
 &amp;lt;/bean&amp;gt;

 &amp;lt;!-- Use the order status map--&amp;gt;
 &amp;lt;bean id="orderNotification" class="test.OrderNotificationImpl"&amp;gt;
  &amp;lt;constructor-arg&amp;gt;
   &amp;lt;ref bean="orderStatus" /&amp;gt;
  &amp;lt;/constructor-arg&amp;gt;
 &amp;lt;/bean&amp;gt;

&amp;lt;/beans&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;STEP 4:&lt;/b&gt; Finally, the standalone client application that makes use of the OrderNotification.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring3 {
    
    public static void main(String[] args) {
        ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
                new String[] {"test/beans3.xml"});
        BeanFactory factory = (BeanFactory) appContext;
        OrderNotification orderNotification = (OrderNotification)factory.getBean("orderNotification");
        orderNotification.processOrder();
       
    }   
}
&lt;/pre&gt;&lt;br /&gt;
If you run the above stand-alone application, you get the following output&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;30/11/2011 4:09:33 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@86c347: startup date [Wed Nov 30 16:09:33 EST 2011]; root of context hierarchy
30/11/2011 4:09:33 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [test/beans3.xml]
30/11/2011 4:09:34 PM org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFO: Loading properties file from class path resource [test/myapp.properties]
30/11/2011 4:09:34 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6c585a: defining beans [propertyPlaceholderConfigurer,orderStatus,orderNotification]; root of factory hierarchy
REJECTED
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How would you go about reading environment specific property files?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; The properties file can be loaded via a file system.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 1:&lt;/b&gt; Have the properties files in an external file system and not within the war or ear archives.  &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 2:&lt;/b&gt; The beans3.xml will have the following change -- change classpath: to file: &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;bean id="propertyPlaceholderConfigurer"
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&amp;gt;
  &amp;lt;property name="locations"&amp;gt;
   &amp;lt;list&amp;gt;
    &amp;lt;value&amp;gt;file:${PROPERTIES_HOME}/test/myapp_${ENV}.properties&amp;lt;/value&amp;gt;
   &amp;lt;/list&amp;gt;
  &amp;lt;/property&amp;gt;
&amp;lt;/bean&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 3: &lt;/b&gt;Provide the JVM arguments PROPERTIES_HOME and ENV.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;java test.TestSpring3 -DPROPERTIES_HOME=C:\\opt2\\myapp   -DENV=dev 
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 4:&lt;/b&gt; The rest remain the same as previous example.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How do you inject a java.util.Properties into your OrderNotification?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 1:&lt;/b&gt; Modify the OrderNotificationImpl as shown below. As you can se the, the java.utilProperties will be injected via setter injection.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

import java.util.Map;
import java.util.Properties;

public class OrderNotificationImpl implements OrderNotification {
    
    private Map&lt;string,string&gt; statuses;
    private Properties appProperties;
    
    public OrderNotificationImpl(Map&lt;string,string&gt; statuses) {
       this.statuses = statuses;
    }

    @Override
    public void processOrder() {
        //....
        System.out.println(statuses.get("REJECTED"));
        System.out.println(appProperties.getProperty("order.status.shipped"));
    }

    public void setAppProperties(Properties appProperties) {
        this.appProperties = appProperties;
    }
}&lt;/string,string&gt;&lt;/string,string&gt;&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 2: &lt;/b&gt;Make some changes to the wiring. The beans4.xml uses the PropertiesFactoryBean and pass it to the PropertyPlaceholderConfigurer. Also, notice that the myappProperties is injected into orderNotification via setter injection. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:jee="http://www.springframework.org/schema/jee"
 xsi:schemaLocation="
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"&amp;gt;


 &amp;lt;bean id="myappProperties"
  class="org.springframework.beans.factory.config.PropertiesFactoryBean"&amp;gt;
  &amp;lt;property name="singleton" value="true" /&amp;gt;

  &amp;lt;property name="ignoreResourceNotFound" value="true" /&amp;gt;
  &amp;lt;property name="locations"&amp;gt;
   &amp;lt;list&amp;gt;
    &amp;lt;value&amp;gt;classpath:test/myapp.properties&amp;lt;/value&amp;gt;
   &amp;lt;/list&amp;gt;
  &amp;lt;/property&amp;gt;
 &amp;lt;/bean&amp;gt;


    &amp;lt;bean id="propertyPlaceholderConfigurer"
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&amp;gt;
  &amp;lt;property name="properties" ref="myappProperties" /&amp;gt; 
 &amp;lt;/bean&amp;gt;

 &amp;lt;!-- inject properties --&amp;gt;
 &amp;lt;bean id="orderStatus" class="java.util.LinkedHashMap"&amp;gt;
  &amp;lt;constructor-arg&amp;gt;
   &amp;lt;map key-type="java.lang.String" value-type="java.lang.String"&amp;gt;
    &amp;lt;entry key="REJECTED"&amp;gt;
     &amp;lt;value&amp;gt;${order.status.rejected}&amp;lt;/value&amp;gt;
    &amp;lt;/entry&amp;gt;
    &amp;lt;entry key="FILLED"&amp;gt;
     &amp;lt;value&amp;gt;${order.status.filled}&amp;lt;/value&amp;gt;
    &amp;lt;/entry&amp;gt;
    &amp;lt;entry key="SHIPPED"&amp;gt;
     &amp;lt;value&amp;gt;${order.status.shipped}&amp;lt;/value&amp;gt;
    &amp;lt;/entry&amp;gt;
   &amp;lt;/map&amp;gt;
  &amp;lt;/constructor-arg&amp;gt;
 &amp;lt;/bean&amp;gt;

 &amp;lt;!-- Use the order status map--&amp;gt;
 &amp;lt;bean id="orderNotification" class="test.OrderNotificationImpl"&amp;gt;
  &amp;lt;constructor-arg&amp;gt;
   &amp;lt;ref bean="orderStatus" /&amp;gt;
  &amp;lt;/constructor-arg&amp;gt;
  &amp;lt;property name="appProperties" ref="myappProperties" /&amp;gt;
 &amp;lt;/bean&amp;gt;

&amp;lt;/beans&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
STEP 3: Finally, modify the TestSpring3 to use beans4.xml.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring3 {
    
    public static void main(String[] args) {
        ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
                new String[] {"test/beans4.xml"});
        BeanFactory factory = (BeanFactory) appContext;
        OrderNotification orderNotification = (OrderNotification)factory.getBean("orderNotification");
        orderNotification.processOrder();     
    }   
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 3:&lt;/b&gt; Finally, modify the TestSpring3 to use beans4.xml.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring3 {
    
    public static void main(String[] args) {
        ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
                new String[] {"test/beans4.xml"});
        BeanFactory factory = (BeanFactory) appContext;
        OrderNotification orderNotification = (OrderNotification)factory.getBean("orderNotification");
        orderNotification.processOrder();     
    }   
}
&lt;/pre&gt;&lt;br /&gt;
The output will be:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;01/12/2011 11:15:55 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1f42b49: startup date [Thu Dec 01 11:15:55 EST 2011]; root of context hierarchy
01/12/2011 11:15:55 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [test/beans4.xml]
01/12/2011 11:15:56 AM org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFO: Loading properties file from class path resource [test/myapp.properties]
01/12/2011 11:15:56 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@12a55aa: defining beans [myappProperties,propertyPlaceholderConfigurer,orderStatus,orderNotification]; root of factory hierarchy
REJECTED
SHIPPED

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How would you use annotations to inject properties?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; Spring 3.0 makes use of annotations, and the properties can be injected   &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&lt;bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" name="propertiesBean" p:location="classpath:test/myapp.properties"&gt;
&lt;/bean&gt;&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;private @Value("${propertyName}") String propertyField;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color: #b45f06; font-size: large;"&gt;More Spring Interview Questions and Answers&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2011/11/spring-interview-questions-and-answers.html"&gt;Spring Interview Questions and Answers : Spring Bean life cycle, DI, and IOC&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.html"&gt;Spring Interview Questions and Answers: Overview&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2011/11/spring-interview-questions-and-answers_30.html"&gt;Spring Interview Questions and Answers: Hibernate integration &lt;/a&gt;&amp;nbsp;&amp;nbsp; &lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-2012877019825103384?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/2cW-DQb1Uyzu9yLlD1XMbKKoaNA/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/2cW-DQb1Uyzu9yLlD1XMbKKoaNA/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/2cW-DQb1Uyzu9yLlD1XMbKKoaNA/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/2cW-DQb1Uyzu9yLlD1XMbKKoaNA/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/kh-4K22oIOo" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/2012877019825103384/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=2012877019825103384" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/2012877019825103384?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/2012877019825103384?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/kh-4K22oIOo/spring-interview-questions-and-answers_29.html" title="Spring Interview Questions and Answers: read properties file" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2011/11/spring-interview-questions-and-answers_29.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0YERnkzcSp7ImA9WhRRFk4.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-7504675089611282782</id><published>2011-11-29T19:01:00.000-08:00</published><updated>2011-11-29T21:31:47.789-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-11-29T21:31:47.789-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="properties" /><title>Java Interview Questions and Answers: working with proprties files</title><content type="html">Managing properties for an enterprise application can be a bit trickier than one might expect.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q: &lt;/b&gt;How would you go about managing properties files in your application?&lt;br /&gt;
&lt;b&gt;A:&lt;/b&gt; One great advantage of property files is that they let you change your application's configuration without recompilation.  However, you most likely need to restart your application for the new configuration to take effect. However, you most likely need to restart your application for the new configuration to take effect. There are different types of properies files like&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;1.&lt;/b&gt; Environment independent files archived within a war or ear. These can be loaded via the classpath.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;classpath:test/myapp.properties
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;2.&lt;/b&gt; Environment independent files stored outside a war or ear. These need to be loaded via a file loader. Define a JVM argument or system property for the path of the file.   &lt;br /&gt;
&lt;pre class="brush: csharp"&gt;file:${PROPERTIES_HOME}/test/myapp.properties
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;3.&lt;/b&gt; Environment specific files stored outside a war or ear. These need to be loaded via a file loader. Define a JVM argument or system property for the path of the file.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;file:${PROPERTIES_HOME}/test/myapp_${my_env}.properties
&lt;/pre&gt;&lt;br /&gt;
It is a best practice to store environment specific (e.g. test, dev, uat, staging, prod, etc)&amp;nbsp; files outside the war or ear archives as the same archive can be deployed to any environment without having to package environment specific archives. &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;4.&lt;/b&gt; Properties file with sensitive information. Store the property values encrypted (Triple DES) or encoded (base64) with a salt. A salt is a secret that can be stored in a database or a separate file with proper access control. &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;5.&lt;/b&gt; Dynamic information in properties file or loading a property file at runtime. For example, in your .properties file you can use&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;#messages
greeting=Welcome Mr. {0} {1} !!!
&lt;/pre&gt;&lt;br /&gt;
Then use the MessageFormat class in Java &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;MessageFormat.format((String) props.get("greeting"), firstName, lastName);
&lt;/pre&gt;&lt;br /&gt;
You can also dynamically load .properties file with the load and store methods in java.util.Properties.  It is recommended to use an existing configuration library like Apache Commons Configuration to load properties file at runtime without having to bring the server or application down. The commons config does support variable interpolation.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;application.title = ${application.name} ${application.version}
&lt;/pre&gt;&lt;br /&gt;
Finally you can use JMX (Java Management eXtension)  to write your own managed bean to change proprty values at runtime. A typical real life example would be to change log4j.xml debug levels.  Appropriate log levels are very handy in diagnosing problems in production, but log levels like trace or debug can adversely impact performance. Hence, it is very useful to be able to set log levels at runtime.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a sample .properties file that can be used with Apache's commons configuration.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;#database - encrypted
db.password=654fdgtr45#1232

#database - clear
db.host=localhost
db.user=john

#messages
greeting=Welcome Mr. {0} {1} !!!

#statuses
order.status.rejected=REJECTED
order.status.filled=FILLED
order.status.shipped=SHIPPED


# lists and arrays
colors.pie = #FF0000, #00FF00, #0000FF

#File includes -- include other .properties files
include = email.properties
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How would you load a properties file from a classpath or a file system?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; Here is a very basic code snippet. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;

public class PropertiesUtil {

    public static Properties loadFromClassPath(String fileName) throws Exception {
        Properties props = new Properties();
        URL url = ClassLoader.getSystemResource(fileName);
        props.load(url.openStream());
        System.out.println(props);
        return props;
    }
    
    public static Properties loadFromFile(File propsFile) throws IOException {
        Properties props = new Properties();
        FileInputStream fis = new FileInputStream(propsFile);
        props.load(fis);    
        fis.close();
        System.out.println(props);
        return props;
    }
    
    public static void main(String[] args)  throws Exception {
        loadFromClassPath("test/myapp.properties");
        loadFromFile(new File("C:\\opt2\\myapp\\test\\myapp.properties"));
    }
}

&lt;/pre&gt;&lt;br /&gt;
Spring has the ability to load properties files as part of the application configuration, for use internally. The properties can be referenced within spring configuration files using ant-style placeholders, e.g. ${app.var}. Here is the link to step by step tutorial.&lt;br /&gt;
&lt;br /&gt;
&lt;a href="http://java-success.blogspot.com/2011/11/spring-interview-questions-and-answers_29.html"&gt;Spring Interview Questions and Answers: read from properties file&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-7504675089611282782?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/YeLJ7KmarN4s0wGhY_wFD4rEeSE/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/YeLJ7KmarN4s0wGhY_wFD4rEeSE/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/YeLJ7KmarN4s0wGhY_wFD4rEeSE/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/YeLJ7KmarN4s0wGhY_wFD4rEeSE/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/2NCe3DUCPg8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/7504675089611282782/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=7504675089611282782" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/7504675089611282782?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/7504675089611282782?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/2NCe3DUCPg8/java-interview-questions-and-answers.html" title="Java Interview Questions and Answers: working with proprties files" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://java-success.blogspot.com/2011/11/java-interview-questions-and-answers.html</feedburner:origLink></entry><entry gd:etag="W/&quot;Dk8BSHo5eCp7ImA9WhRQEEg.&quot;"><id>tag:blogger.com,1999:blog-35897879.post-3544684451960413933</id><published>2011-11-27T22:26:00.000-08:00</published><updated>2011-12-04T19:14:19.420-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-04T19:14:19.420-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Spring Interview Questions and Answers" /><category scheme="http://www.blogger.com/atom/ns#" term="Dependency Injection" /><category scheme="http://www.blogger.com/atom/ns#" term="Spring interview questions" /><category scheme="http://www.blogger.com/atom/ns#" term="IOC" /><category scheme="http://www.blogger.com/atom/ns#" term="DI" /><category scheme="http://www.blogger.com/atom/ns#" term="Spring" /><title>Spring Interview Questions and Answers : Spring Bean life cycle, DI, and IOC</title><content type="html">&lt;b&gt;Q.&lt;/b&gt; Can you describe the bean life cycle?&lt;br /&gt;
&lt;b&gt;A&lt;/b&gt;. A Spring Bean represents a POJO (Plain Old Java Object) performing useful operation(s). All Spring Beans reside within a Spring IOC Container. The Spring Framework hides most of the complex infrastructure and the communication that happens between the Spring Container and the Spring Beans. The state-chart diagram below highlights these communications.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-zL2kXc0oJLg/TtMpbaHzJRI/AAAAAAAAAQ8/kQi4fMWgP2E/s1600/spring-life-cycle.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="606" src="http://1.bp.blogspot.com/-zL2kXc0oJLg/TtMpbaHzJRI/AAAAAAAAAQ8/kQi4fMWgP2E/s640/spring-life-cycle.JPG" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;b&gt;Q. &lt;/b&gt;What is a BeanFactory?   &lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; The BeanFactory is the actual container which instantiates, configures, and manages a number of beans. These beans typically collaborate with one another, and thus have dependencies between themselves. &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How would you go about wiring up the spring managed bean dependencies?&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; In general, the dependencies are wired via the Spring config file. For example, the MyBeanService depends on MyBeanDao, and MyBean depends on MyBeanService, etc via either constructor or setter injection.&lt;br /&gt;
&lt;br /&gt;
Here is the big picture of the collaborating classes and interfaces.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-PetlYr4KKBk/TtQ6bDNmvfI/AAAAAAAAARE/PvRuodIdt-s/s1600/spring-beans-injection.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="248" src="http://1.bp.blogspot.com/-PetlYr4KKBk/TtQ6bDNmvfI/AAAAAAAAARE/PvRuodIdt-s/s400/spring-beans-injection.JPG" width="400" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
Here are the libraries ( highlighted in blue rectangle) that needs to be in the classpath.The commons-logging is used by the spring-beans-xx.jar.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-ezpGifbYlYs/TtQ6shfqAxI/AAAAAAAAARM/3VlLYqueSXE/s1600/spring-beans-lib.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="258" src="http://4.bp.blogspot.com/-ezpGifbYlYs/TtQ6shfqAxI/AAAAAAAAARM/3VlLYqueSXE/s320/spring-beans-lib.JPG" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 1:&lt;/b&gt; Firstly define the relevant interfaces. Coding to interfaces is a good design parctice that loosely couples your classes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

public interface MyBeanDao {
   abstract void daoMethod();
}
&lt;/pre&gt;&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

public interface MyBeanService {
    abstract void serviceMethod();
}
&lt;/pre&gt;&lt;br /&gt;
Now, define the concrete implementation for the above interfaces.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

public class MyBeanDaoImpl implements MyBeanDao {

    @Override
    public void daoMethod() {
        System.out.println("dao method invoked ...");
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

public class MyBeanServiceImpl implements MyBeanService {
    
    private MyBeanDao beanDao;

    @Override
    public void serviceMethod() {
       System.out.println("Service method invoked...");
       beanDao.daoMethod();
    }
    
    public void setBeanDao(MyBeanDao beanDao) {
        System.out.println("setter injection .....");
        this.beanDao = beanDao;
    }  
}
 
&lt;/pre&gt;&lt;br /&gt;
Next, define the MyBean class that makes use of the MyBeanService and the &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

public class MyBean {
    
    private MyBeanService beanService;
    
    public MyBean(MyBeanService beanService) {
        System.out.println("Constructor injection...");
        this.beanService = beanService;
    }
    
    public void testMethod(){
        System.out.println("My bean method invoked ....");
        beanService.serviceMethod();
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;STEP 2:&lt;/b&gt; Wire up the beans and the dependencies via an IOC container like Spring. The beans.xml file is shown below.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:jee="http://www.springframework.org/schema/jee" 
 xsi:schemaLocation="
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"&amp;gt;

 &amp;lt;bean id="myBeanDao" class="test.MyBeanDaoImpl"/&amp;gt;
 
 &amp;lt;bean id="myBeanService" class="test.MyBeanServiceImpl"&amp;gt;
    &amp;lt;!-- setter injection of dao into service --&amp;gt;
    &amp;lt;property name="beanDao" ref="myBeanDao" /&amp;gt;
 &amp;lt;/bean&amp;gt;
 
 &amp;lt;bean id="myBean" class="test.MyBean"&amp;gt; 
    &amp;lt;!-- constructor injection of service into mybean --&amp;gt;
    &amp;lt;constructor-arg&amp;gt;&amp;lt;ref bean="myBeanService" /&amp;gt;&amp;lt;/constructor-arg&amp;gt;
 &amp;lt;/bean&amp;gt;
 
&amp;lt;/beans&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
As you can see, the MyBeanDao is injected via the setter injection into MyBeanService, and the MyBeanService is injected into MyBean via the constructor injection.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q. &lt;/b&gt;How do you bootstrap the initial bean?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 3:&lt;/b&gt; The TestSpring class is the client class that makes use of the MyBean. In order to access the  initial entry point into your application, which in this case is "MyBean", it needs to be bootstrapped via a BeanFactory implementation class. It can be done a number of ways as demonstrated below.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Using the "ClassPathXmlApplicationContext" &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {
    
    public static void main(String[] args) {
        ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
                new String[] {"test/beans.xml"});
        BeanFactory factory = (BeanFactory) appContext;
        MyBean bean = (MyBean)factory.getBean("myBean"); 
        bean.testMethod();  
    }   
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Using the "FileSystemResource"&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class TestSpring {
    
    public static void main(String[] args) {
        Resource res = new FileSystemResource("bin/test/beans.xml");
        XmlBeanFactory factory = new XmlBeanFactory(res);
        MyBean bean = (MyBean)factory.getBean("myBean"); 
        bean.testMethod();  
    }   
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Using the "ClassPathResource"&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class TestSpring {
    
    public static void main(String[] args) {
        ClassPathResource res = new ClassPathResource("test/beans.xml");
        XmlBeanFactory factory = new XmlBeanFactory(res);
        MyBean bean = (MyBean)factory.getBean("myBean"); 
        bean.testMethod();  
    }   
}
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;STEP 4: &lt;/b&gt;Run the TestSpring as a stand alone application, which prints the following.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;setter injection .....
Constructor injection...
My bean method invoked ....
Service method invoked...
dao method invoked ...
&lt;/pre&gt;&lt;br /&gt;
When &lt;i&gt;   MyBean bean = (MyBean)factory.getBean("myBean");  i&lt;/i&gt;s executed, the dependent beans are created and wired up by the IOC container. You can further extend this by providing the necessary hooks to further enhance your understanding.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; What would you do if it’s not practical (or impossible) to wire up your entire application into the Spring framework, but you still need a Spring loaded bean in order to perform a task?&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;A.&lt;/b&gt; For example, &lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;an auto generated web service client class! But you do want to use the dependency injection feature of Spring to get some of the other beans injected in to this class. &lt;/li&gt;
&lt;li&gt;A legacy code that needs to make use of a Spring bean.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
The ApplicationContextAware interface provided by Spring allows you to wire some java classes which are unable (or you don’t want it) to be wired to the Spring application context.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 1:&lt;/b&gt; The ApplicationContextAware interface makes sense when an object requires access to a set of collaborating beans. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class MyServiceFactory implements ApplicationContextAware {
    
    private ApplicationContext context;

    public void testMethod2(){
        System.out.println("Test method2 invoked ....");
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx)
            throws BeansException {
       System.out.println("setting application context ..."); 
       this.context = ctx;
    }
    
    
    public MyBeanService getInstance(String accessCode) {
        //.....some logic
        MyBeanService beanService = (MyBeanService) context.getBean("myBeanService");
        return beanService;
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;STEP 2:&lt;/b&gt; The beans2.xml file. The &lt;i&gt;MyServiceFactory &lt;/i&gt;is not wired up.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:jee="http://www.springframework.org/schema/jee" 
 xsi:schemaLocation="
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"&amp;gt;
 
 
 &amp;lt;bean id="myBeanDao" class="test.MyBeanDaoImpl"/&amp;gt;
 
 &amp;lt;bean id="myBeanService" class="test.MyBeanServiceImpl"&amp;gt;
    &amp;lt;!-- setter injection of dao into service --&amp;gt;
    &amp;lt;property name="beanDao" ref="myBeanDao" /&amp;gt;
 &amp;lt;/bean&amp;gt;
 
 &amp;lt;!-- No DI wiring --&amp;gt;
 &amp;lt;bean id="myServiceFactory" class="test.MyServiceFactory" /&amp;gt; 
   
&amp;lt;/beans&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;STEP 3: &lt;/b&gt;Finally, the client code that makes use of the &lt;i&gt;MyServiceFactory &lt;/i&gt;class.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring2 {
    
    public static void main(String[] args) {
        ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
                new String[] {"test/beans2.xml"});
        BeanFactory factory = (BeanFactory) appContext;
        MyServiceFactory servicefactory = (MyServiceFactory)factory.getBean("myServiceFactory"); 
        MyBeanService service = servicefactory.getInstance("111");
        service.serviceMethod();
    }   
}&lt;/pre&gt;&lt;br /&gt;
The output will be:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;29/11/2011 3:59:29 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@145e044: startup date [Tue Nov 29 15:59:29 EST 2011]; root of context hierarchy
29/11/2011 3:59:29 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [test/beans2.xml]
29/11/2011 3:59:29 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1a42792: defining beans [myBeanDao,myBeanService,myServiceFactory]; root of factory hierarchy
setter injection .....
setting application context ...
Service method invoked...
dao method invoked ...
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Q.&lt;/b&gt; How would you create an application context from a web application?&lt;br /&gt;
&lt;b&gt;A. &lt;/b&gt;As opposed to the BeanFactory, which will often be created programmatically, ApplicationContexts can be created declaratively using a ContextLoader. You can register an ApplicationContext using the ContextLoaderListener as shown below in the web.xml file. The Spring context listener provides more flexibility in terms of how an application is wired together. It uses the application's Spring configuration to determine what object to instantiate and loads the objects into the application context used by the servlet container.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;web-app&amp;gt;
  .....
  &amp;lt;listener&amp;gt;
     &amp;lt;listener-class&amp;gt;org.springframework.web.context.ContextLoaderListener&amp;lt;/listener-class&amp;gt;
  &amp;lt;/listener&amp;gt;
  ....
&amp;lt;/web-app&amp;gt; 
&lt;/pre&gt;&lt;br /&gt;
By default, it looks for a file named applicationContext.xml file in WEB-INF folder. But, you can configure the org.springframework.web.context.ContextLoaderListener class to use a context parameter called contextConfigLocation to determine the location of the Spring configuration file. The context parameter is configured using the context-parameter element. The context-param element has two children that specify parameters and their values. The param-name element specifies the parameter's name. The param-value element specifies the parameter's value.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;web-app&amp;gt;
  ...
  &amp;lt;context-param&amp;gt;
    &amp;lt;param-name&amp;gt;contextConfigLocation&amp;lt;/param-name&amp;gt;
    &amp;lt;param-value&amp;gt;WEB-INF/beans.xml&amp;lt;/param-value&amp;gt;
  &amp;lt;/context-param&amp;gt;

  &amp;lt;listener&amp;gt; 
    &amp;lt;listener-class&amp;gt;org.springframework.web.context.ContextLoaderListener&amp;lt;/listener-class&amp;gt;
  &amp;lt;/listener&amp;gt;
  ...
&amp;lt;/web-app&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
Note: There will be only one ServletContext for each web application. ServletContext will be created while deploying the application. Once the ServletContext is created, it will be used by all the servlets and jsp files in the same application. ServletContext is also called as the application scope variables in the web application scenario. The ContextLoaderListener is in the spring-web-xxx.jar.  It is quite handy to check the Spring API for org.springframework.web.context.support.XmlWebApplicationContext class that describes this. &lt;br /&gt;
&lt;br /&gt;
For a WebApplicationContext that reads in a different bean definition format, you could define your own implementation, and define your implementation with the "contextClass" init parameter.&lt;br /&gt;
&lt;br /&gt;
Here is another example with multiple Spring files.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;&amp;lt;webapp&amp;gt;
   ..
   &amp;lt;context-param&amp;gt;
  &amp;lt;param-name&amp;gt;contextClass&amp;lt;/param-name&amp;gt;
  &amp;lt;param-value&amp;gt;com.myapp.MyappXmlWebApplicationContext&amp;lt;/param-value&amp;gt;
 &amp;lt;/context-param&amp;gt;

   &amp;lt;context-param&amp;gt;
  &amp;lt;param-name&amp;gt;contextConfigLocation&amp;lt;/param-name&amp;gt;
  &amp;lt;param-value&amp;gt;
   classpath*:/com/myapp/transactionContext.xml
   classpath*:/com/myapp/daoContext.xml  
   classpath*:/com/myapp/override-daoContext${my.env}.xml
            /WEB-INF/webservice-interceptor-config.xml
   /WEB-INF/webservice-config.xml
   classpath*:/cxf.xml
  &amp;lt;/param-value&amp;gt;
 &amp;lt;/context-param&amp;gt;   
 
   &amp;lt;listener&amp;gt; 
       &amp;lt;listener-class&amp;gt;org.springframework.web.context.ContextLoaderListener&amp;lt;/listener-class&amp;gt;
   &amp;lt;/listener&amp;gt;
   
&amp;lt;/web-app&amp;gt;

&lt;/pre&gt;&lt;br /&gt;
The contextClass can be defined something like.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;package com.myapp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.context.support.ServletContextResourcePatternResolver;
import org.springframework.web.context.support.XmlWebApplicationContext;

public class MyappXmlWebApplicationContext extends XmlWebApplicationContext {
    private static final String MY_ENV = "my.env";
    private static final String MY_ENV_PLACEHOLDER = "\\$\\{" + MY_ENV + "\\}";

    protected ResourcePatternResolver getResourcePatternResolver() {
        return new PatchedResourcePatternResolver(this);
    }

    private static class PatchedResourcePatternResolver extends ServletContextResourcePatternResolver {

        public PatchedResourcePatternResolver(ResourceLoader resourceLoader) {
            super(resourceLoader);
        }

        public Resource[] getResources(String locationPattern) throws IOException {
            locationPattern = locationPattern.replaceAll(MY_ENV_PLACEHOLDER, System.getProperty(MY_ENV, ""));
            Resource[] resources = super.getResources(locationPattern);

            if (0 &amp;lt; locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()).length()) {
                return resources;
            }

            Collection&amp;lt;Resource&amp;gt; filteredResources = new ArrayList&amp;lt;Resource&amp;gt;();
            for (int i = 0; i &amp;lt; resources.length; i++) {
                Resource resource = resources[i];
                if (!resource.getURL().getProtocol().equals("jar")) {
                    filteredResources.add(resource);
                }
            }
            return (Resource[]) filteredResources.toArray(new Resource[filteredResources.size()]);
        }
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style="color: #b45f06; font-size: large;"&gt;More Spring Interview Questions and Answers&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.html"&gt;Spring Interview Questions and Answers: Overview   &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2011/11/spring-interview-questions-and-answers_29.html"&gt;Spring Interview Questions and Answers: read properties file       &lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://java-success.blogspot.com/2011/11/spring-interview-questions-and-answers_30.html"&gt;Spring Interview Questions and Answers: Hibernate integration &lt;/a&gt;&amp;nbsp;&amp;nbsp; &lt;/li&gt;
&lt;/ul&gt;&lt;a href="http://java-success.blogspot.com/2011/10/spring-interview-questions-and-answers.html"&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35897879-3544684451960413933?l=java-success.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/l4QoiVWGuMJMNmVwjv316oHcO7I/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/l4QoiVWGuMJMNmVwjv316oHcO7I/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/l4QoiVWGuMJMNmVwjv316oHcO7I/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/l4QoiVWGuMJMNmVwjv316oHcO7I/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Java/JEECareerCompanion/~4/4w0Lk1MzXdQ" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://java-success.blogspot.com/feeds/3544684451960413933/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=35897879&amp;postID=3544684451960413933" title="3 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/3544684451960413933?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/35897879/posts/default/3544684451960413933?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Java/JEECareerCompanion/~3/4w0Lk1MzXdQ/spring-interview-questions-and-answers.html" title="Spring Interview Questions and Answers : Spring Bean life cycle, DI, and IOC" /><author><name>Arulkumaran.K</name><uri>http://www.blogger.com/profile/00869496028596976417</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://2.bp.blogspot.com/_5WpgLGIKwOI/TPYeUI3VToI/AAAAAAAAACA/IFDHZUdt7Mk/s1600-R/picture-252543.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://1.bp.blogspot.com/-zL2kXc0oJLg/TtMpbaHzJRI/AAAAAAAAAQ8/kQi4fMWgP2E/s72-c/spring-life-cycle.JPG" height="72" width="72" /><thr:total>3</thr:total><feedburner:origLink>http://java-success.blogspot.com/2011/11/spring-interview-questions-and-answers.html</feedburner:origLink></entry></feed>

