Java Interview Questions -42

Java Interview Questions -42

1.What is an Aspect?

An aspect is the cross-cutting functionality that you are implementing. It is the aspect of your application you are modularizing. An example of an aspect is logging. Logging is something that is required throughout an application. However, because applications tend to be broken down into layers based on functionality, reusing a logging module through inheritance does not make sense. However, you can create a logging aspect and apply it throughout your application using AOP.

2.What is a Jointpoint?

A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being called, an exception being thrown, or even a field being modified. These are the points where your aspect’s code can be inserted into the normal flow of your application to add new behaviour.

3.What is an Advice?

Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, and advice is inserted into an application at joinpoints.

4.What is IOC (or Dependency Injection)?

The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.
i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

5.What are the different types of IOC (dependency injection) ?

There are three types of dependency injection:
i.Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
ii.Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
iii.Interface Injection (e.g. Avalon): Injection is done through an interface.

6.Explain about the Spring DAO support ?

The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the persistence technologies fairly easily and it also allows one to code without worrying about catching exceptions that are specific to each technology.

7.What are the exceptions thrown by the Spring DAO classes ?

Spring DAO classes throw exceptions which are subclasses of DataAccessException(org.springframework.dao.DataAccessException).Spring provides a convenient translation from technology-specific exceptions like SQLException to its own exception class hierarchy with the DataAccessException as the root exception. These exceptions wrap the original exception.

8.What is SQLExceptionTranslator ?

SQLExceptionTranslator, is an interface to be implemented by classes that can translate between SQLExceptions and Spring’s own data-access-strategy-agnostic org.springframework.dao.DataAccessException.

9.What are the benefits of IOC (Dependency Injection)?

Benefits of IOC (Dependency Injection) are as follows:
Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.
Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.
Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own.
IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.

10.What are the ways to access Hibernate using Spring ?

There are two approaches to Spring’s Hibernate integration:
 i.Inversion of Control with a HibernateTemplate and Callback
 ii.Extending HibernateDaoSupport and Applying an AOP Interceptor

11.How to integrate Spring and Hibernate using HibernateDaoSupport?

Spring and Hibernate can integrate using Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps.
   i.Configure the Hibernate SessionFactory
  ii.Extend your DAO Implementation from HibernateDaoSupport
  iii.Wire in Transaction Support with AOP

12.What is AOP?

Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules.

13.How the AOP used in Spring?

AOP is used in the Spring Framework: To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on the Spring Framework’s transaction abstraction.To allow users to implement custom aspects, complementing their use of OOP with AOP.

14.What do you mean by Aspect ?

A modularization of a concern that cuts across multiple objects. Transaction management is a good example of a crosscutting concern in J2EE applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (@AspectJ style).

15.What do you mean by JointPoint?

A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.

16.What do you mean by Advice?

Action taken by an aspect at a particular join point. Different types of advice include “around,” “before” and “after” advice. Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors “around” the join point.

17.Why most users of the Spring Framework choose declarative transaction management ?

Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on application code, and hence is most consistent with the ideals of a non-invasive lightweight container.

18.When to use programmatic and declarative transaction management ?

Programmatic transaction management is usually a good idea only if you have a small number of transactional operations.On the other hand, if your application has numerous transactional operations, declarative transaction management is usually worthwhile. It keeps transaction management out of business logic, and is not difficult to configure.

19.What is Spring’s JdbcTemplate ?

Spring’s JdbcTemplate is central class to interact with a database through JDBC. JdbcTemplate provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling.
JdbcTemplate template = new JdbcTemplate(myDataSource);

20.What is PreparedStatementCreator ?

PreparedStatementCreator:
i.Is one of the most common used interfaces for writing data to database.
2.Has one method – createPreparedStatement(Connection)
3.Responsible for creating a PreparedStatement.
4.Does not need to handle SQLExceptions.

21.What is SQLProvider ?

SQLProvider:
1.Has one method – getSql()
ii.Typically implemented by PreparedStatementCreator implementers.
iii.Useful for debugging.

22..What is Hibernate proxy?

The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.

23.How can Hibernate be configured to access an instance variable directly and not through a setter method ?

By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

24.How can a whole class be mapped as immutable?

Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.

25.What is the use of dynamic-insert and dynamic-update attributes in a class mapping?

Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed
dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

26.What do you mean by fetching strategy ?

A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.

27.What is automatic dirty checking?

Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.

28. What is RowCallbackHandler ?

The RowCallbackHandler interface extracts values from each row of a ResultSet.
Has one method – processRow(ResultSet)
Called for each row in ResultSet.
Typically stateful.

29.Define cascade and inverse option in one-many mapping?

cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"
inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

30.What is transactional write-behind?

Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.

31.What are Callback interfaces?

Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.

32.What are the types of Hibernate instance states ?

Three types of instance states:
Transient -The instance is not associated with any persistence context
Persistent -The instance is associated with a persistence context
Detached -The instance was associated with a persistence context which has been closed – currently not associated

33.What makes J2EE appropriate for dispersed/distributed multitiered WEB Applications ?

J2EE platform follows a multi-tiered distributed application model. Application logic is distributed into components according to role, and the different application components that make up a J2EE application are installed on different machines depending on the tier in the multi-tiered J2EE environment to which the application component belongs. The J2EE application parts are:
• Client-tier component runs on the client machine.
• Web-tier component runs on the J2EE server.
• Business-tier component runs on the J2EE server.
• Enterprise Information System tier software runs on the EIS server.

34.What are different components of J2EE application ?

A J2EE component is a self-contained functional software entity that is combined into a J2EE application with its related classes, files and intracts with other components. The J2EE defines the given below J2EE components:
• Application clients and applets act as client components.
• Java Servlet and JavaServer Pages act as web components.
• Enterprise JavaBeans(EJB) components act as business components.
• Resource adapter components delivered by EIS and tool vendors.

35.What is Enterprise JavaBeans component ?

Enterprise JavaBeans components comprises Business code, which is logic that fulfill the requirements of a particular business domain such as retail, banking , telecom or finance. All business code is enclosed inside an Enterprise Bean which gets data from client, processes it, and sends it to the enterprise information system tier for persistence. An enterprise bean also fetches data from storage, processes it and sends it back to the client program.

36.What is the container ?

It is the interface between a component and the low-level platform centric functionality that supports the component. Container contains and manages the execution and lifecycle of components. Before a Web, enterprise bean, or application client component can be executed, it must be integrated into a J2EE application and deployed into its container.

37.What is deployment descriptor ?

A deployment descriptor is an XML text-based file with an .xml extension that describes about component’s deployment settings. A J2EE application and its every modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor describes transaction settings and security authorizations
settings for an enterprise bean. As deployment descriptor information is declarative, it can be modified without altering the bean source code. At run time, the J2EE server reads the deployment descriptor and executes component accordingly.

38.What are the implicit objects ?

Implicit objects are objects which are created by the web container and contain information about a particular request, page, or application. Implicit objects are : request, response, pageContext, session, application, out, config, page, exception.

39.How does JSP handle run-time exceptions?

You can use the errorPage attribute of the page directive to handle uncaught run-time exceptions and so automatically forwarded to an error processing page. For example: <%@ page errorPage=”error.jsp” %> redirects the browser to page error.jsp if an uncaught exception occured during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage=”true” %> then Throwable object describing the exception may be accessed within the error page via the ‘exception’ implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.

40.What is a Declaration ?

A declaration has one or more variables or methods declared for use later in the JSP source file.
It must contain at least one declarative statement. Any number of variables or methods within one declaration tag, as long as they are separated by semicolons.
<%! int i = 0; %>
<%! int a, b, c; %>

41.What is a Scriptlet ?

A scriptlet can contain any number of language statements, variable or method declarations/defination, or expressions which are valid in the page scripting language.Within scriptlet tags, you can
Declare variables or methods .Write expressions that are valid in the page scripting language.Use JSP implicit objects or any object declared with a <jsp:useBean> tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet tag.Scriptlets are executed by JSP engine request time. If the scriptlet generates output, the output is saved in the out object.

42.What is a output comment ?

A comment which is sent to the client in the viewable page source. The JSP engine treats an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. Comment can be seen by viewing the page source from your Web browser.
JSP Syntax
<!– comment [ <%= expression %> ] –>
Example 1
<!– commnet sent to client on
<%= (new java.util.Date()).toLocaleString() %>
–>
Displays in the page source:
<!– commnet sent to client on January 20, 2012 –>

43.What is a Hidden Comment ?

A comments that is not sent to the client. The JSP engine ignores a hidden comment, and does not process any of the code within hidden comment. A hidden comment is not sent to the client, either in the shown JSP page or the HTML page source. The hidden comment is useful when you don’t want to execute some part of your JSP page.
You can use any characters in the comment except the closing –%> tag. If you want to use –%> in your comment, you can escape it by typing –%\>.
JSP Syntax
<%– comment –%>
Examples
<html>
<head><title>A Hidden Comment </title></head>
<body>
<%– This comment is not visible to the client in the page source –%>
</body>
</html>

44.Explain the life cycle methods of a Servlet ?

The javax.servlet.Servlet interface defines the three methods called as life-cycle method.

public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
First the servlet is constructed, then servlet is initialized wih the init() method.
Any request from client is handled by the service() method before delegating to the doGet()/doPost() methods in the case of HttpServlet.
Ffter service method finished , container removes servlet out of service, it calls the servlet’s destroy() method.

45.Differentiate between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?

The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface takes parameter the path to the resource to be included or forwarded to, that can be relative to the request of the calling servlet. If the path begins with a “/” it is interpreted as relative to the current context root.
The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot take relative paths. All path must sart with a “/” and are interpreted as relative to current context root.

46.Describe the directory structure of a web application ?

The directory structure of a web application composed of two parts.
A private directory WEB-INF
A public resource directory which contains public resource folder.
WEB-INF folder consists of
• web.xml (deployment descriptor)
• classes directory containing .class files
• lib directory containing jar files

47.How do I prevent the output of my JSP or Servlet pages from being cached by the browser?

Just write the following scriptlet code at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.
 <%
response.setHeader(“Cache-Control”,”no-store”); //HTTP 1.1
response.setHeader(“Pragma”,”no-cache”); //HTTP 1.0
response.setDateHeader (“Expires”, 0); //prevents caching at the proxy server
 %>

48.How a servlet is preinitialized ?

A container does not initialize the servlets on its start up, it initializes a servlet when it receives a request for that servlet first time that is called lazy loading. A servlet can be loaded at the start up of the container by using <load-on-startup> 1</load-on-startup> element, which can be specified in web.xml. This process of loading a servlet at start up of container is called preloading or preinitializing a servlet.

49.How do I use comments within a JSP page?

You can use “JSP-style” comments to selectively block out some code during debugging or simply to comment your scriptlets. JSP comments are not visible at the client side. For example:
<%– the scriptlet is now commented out
<% out.println(“Hello World”);%>
–%>
You can also put HTML-style comments within your JSP page. These comments are visible at the client. For example:
<!– (c) 2004 –>
Of course, you can also use comments supported by your JSP scripting language within the scriptlets. For example, assuming Java is the scripting language, you can write:
<%
//some comment
/**
another comment
**/
%>
doPost is when a HTTP POST request is made. This happens with HTML FORMs (those with METHOD=”POST” specified in the FORM tag). In doPost method , form data is sent in separate line in the body. Data that can be sent is not limited. Parameters are sent in encrypted form. DoPost is slower compared to doGet since doPost does not write the content response length.

50.What is the difference between ServletContext and ServletConfig ?

ServletContext: Defines a set of methods which help servlet to communicate with its servlet container, for example, to get the MIME type , dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized . The ServletContext object signifies the context for the whole Web application in which a servlet is deployed, and contains initialisation parameters that are available to all servlets in the application.
ServletConfig: ServletConfig is a servlet configuration object that is used by a servlet container used to pass information/data to a servlet during initialization. All of its initialization parameters can ONLY be set in deployment descriptor.The ServletConfig object represents the configuration for a single specific servlet. The ServletConfig parameters are ment for a particular servlet and are unknown to other servlets.

51.Explain the life cycle methods of a Servlet ?

The javax.servlet.Servlet interface defines the three methods called as life-cycle method.
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
First the servlet is constructed, then servlet is initialized wih the init() method.Any request from client is handled by the service() method before delegating to the doGet()/doPost() methods in the case of HttpServlet.
Ffter service method finished , container removes servlet out of service, it calls the servlet’s destroy() method.

52.Differentiate between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?

The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface takes parameter the path to the resource to be included or forwarded to, that can be relative to the request of the calling servlet. If the path begins with a “/” it is interpreted as relative to the current context root.
The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot take relative paths. All path must sart with a “/” and are interpreted as relative to current context root.

53.Explain ServletContext ?

ServletContext interface act as a window for a servlet to view it’s surroundings . A servlet can use this interface to get information such as initialization parameters for the web application or servlet container. Every web application has only one ServletContext that is accessible to all active resource of that application.

54.How a servlet is preinitialized ?

A container does not initialize the servlets on its start up, it initializes a servlet when it receives a request for that servlet first time that is called lazy loading. A servlet can be loaded at the start up of the container by using <load-on-startup> 1</load-on-startup> element, which can be specified in web.xml. This process of loading a servlet at start up of container is called preloading or preinitializing a servlet.

55.What is the difference between doGet() and doPost() ?

doGet is called when a HTTP GET request is made. doGet() is called when users click on a link, or enter a URL into the browser’s address bar. It also happens with some HTML FORMs (those with METHOD=”GET” specified in the FORM tag). In doGet Method the parameters are appended to the URL and sent along with header information.
Maximum size of data that can be sent is limited. Parameters sent are not encrypted . DoGet is faster if we set the response content length since the same connection is used. Thus increasing the performance
doPost is when a HTTP POST request is made. This happens with HTML FORMs (those with METHOD=”POST” specified in the FORM tag). In doPost method , form data is sent in separate line in the body. Data that can be sent is not limited. Parameters are sent in encrypted form. DoPost is slower compared to doGet since doPost does not write the content response length.

56.Difference between forward and sendRedirect ?

Both forward and sendRedirect methods are used to transfer the control from one resource to another.
forward : When you transfer the control to another resource by invoking a forward request, the request is sent to another resource on the server, without the client being informed about the fact that a different resource is going to process the request. This process occurs completely with in the web container, browser or client don’t perform any role in this. When the forward request is done, the original request and response objects are transferred and in the other resource to which the control is passed can get these objects. In forward request URL in the browser does not change.
sendRedirect : In sendRedirect the transfer of control task is delegated to the browser by the container. A header information is sent back to the browser / client when sendRedirect is invoked. This header information contains the resource url to be redirected by the browser. Then the browser make a new request to the given url and URL in browser gets changed. As it is a new request, the old request and response object is lost.


57.What is the difference between HttpServlet and GenericServlet ?

javax.servlet.GenericServlet
• GenericServlet is a generic, protocol-independent servlet.
• GenericServlet gives a template and makes creating servlet easier.
• GenericServlet delivers simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface.
• GenericServlet implements the log method which is declared in the ServletContext interface.
• To use a generic servlet, it is sufficient to override the abstract service method.
javax.servlet.http.HttpServlet
• HttpServlet is specific to HTTP protocol.
• HttpServlet gives a template for Http servlet and makes creating them easier.
• HttpServlet extends the GenericServlet and hence inherits the traits of GenericServlet.

58.What are container services ?

A container act as a runtime support of a system-level entity. Containers provide components with different services such as lifecycle management, security, deployment, and threading.

59. What is the web container ?

Servlet and JSP containers are called Web containers. It manages the execution and lifecycle of JSP page and servlet components for J2EE applications. Web components and their container

60. What is Applet container ?

It manages the execution of applets, comprises of a Web browser and Java Plugin assembled on the client together.

61.What is a thin client ?

A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications. A thin client is portion of a network, and the client software or computer acts as an interface, while the network server computer performs all the actual work.

62.What is J2EE(Java2 enterprise edition) ?

J2EE is platform for developing and deploying enterprise Web applications. The J2EE platform contains a set of services, application programming interfaces (APIs), and protocols that offer the functionality for developing multi-tiered, web-based applications.

63.Are J2EE applications only a web-based ?

No, It depends on type of application that client wants to have. A J2EE application can be both web-based or non web-based. If an application runs on the client machine, it is a non web-based J2EE application.

64.Is HTML page a web component ?

No. Static HTML pages and applets are bundled into web components during application assembly, but are not supposed web components by the J2EE specification. Even the server-side utility classes are not supposed web components, either.

65.What is the EAR file ?

An EAR file is a standard JAR file having .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file.

66.What are the different ways for session tracking ?

Cookies, HttpSession, URL rewriting, Hidden form fields

67.What is spring framework? Why Java programmer should use Spring framework

This is a Very common Spring interview question, Spring is a framework which helps Java programmer in development. Spring is a modular framework. Spring provides dependency Injection and IOC container, Spring MVC flow and several useful API for Java programmer.

68.What is default scope of bean in Spring framework ?

The Default scope of bean is Singleton.

69.Does Spring singleton beans are thread-safe ?

No, Spring singleton beans are not thread-safe. Singleton doesn’t mean bean would be thread-safe.

70.What are object/relational mapping integration module?

Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provide support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction management supports each of these ORM frameworks as well as JDBC.

71.What is web module?

Spring comes with a full-featured MVC framework for building web applications. Although Spring can easily be integrated with other MVC frameworks, such as Struts, Spring’s MVC framework uses IoC to provide for a clean separation of controller logic from business objects. It also allows you to declaratively bind request parameters to your business objects. It also can take advantage of any of Spring’s other services, such as I18N messaging and validation.

72.What is a BeanFactory?

A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s configuration and dependencies from the actual application code.

73.What is AOP Alliance?

AOP Alliance is an open-source project whose goal is to promote adoption of AOP and interoperability among different AOP implementations by defining a common set of interfaces and components.

74.What is Spring configuration file?

Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.

75.What does a simple spring application contain?

These applications are like any Java application. They are made up of several classes, each performing a specific purpose within the application. But these classes are configured and introduced to each other through an XML file. This XML file describes how to configure the classes, known as the Spring configuration file.

76.What is XMLBeanFactory?

BeanFactory has many implementations in Spring. But one of the most useful one is org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. To create an XmlBeanFactory, pass a java.io.InputStream to the constructor. The InputStream will provide the XML to the factory. For example, the following code snippet uses a java.io.FileInputStream to provide a bean definition XML file to XmlBeanFactory.
  BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));
  To retrieve the bean from a BeanFactory, call the getBean() method by passing the name of the bean you want to retrieve.
  MyBean myBean = (MyBean) factory.getBean("myBean");

77.What are important ApplicationContext implementations in spring framework?

ClassPathXmlApplicationContext – This context loads a context definition from an XML file located in the class path, treating context definition files as class path resources.
FileSystemXmlApplicationContext – This context loads a context definition from an XML file in the filesystem.
XmlWebApplicationContext – This context loads the context definitions from an XML file contained within a web application.

78.Explain Bean lifecycle in Spring framework?

The spring container finds the bean’s definition from the XML file and instantiates the bean.
Using the dependency injection, spring populates all of the properties as specified in the bean definition.
if the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.If an init-method is specified for the bean, it will be called.
Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

79.What is bean wiring?

Combining together beans within the Spring container is known as bean wiring or wiring. When wiring beans, you should tell the container what beans are needed and how the container should use dependency injection to tie them together.

80.How do add a bean in spring application?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="foo" class="com.act.Foo"/>
<bean id="bar" class="com.act.Bar"/>
</beans>
In the bean tag the id attribute specifies the bean name and the class attribute specifies the fully qualified class name.

81.What are singleton beans and how can you create prototype beans?

Beans defined in spring framework are singleton beans. There is an attribute in bean tag named ‘singleton’ if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by default singleton beans.
    <beans>
  <bean id="bar" class="com.act.Foo" singleton=”false”/>
</beans>

82.What are the important beans lifecycle methods?

There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container. The second method is the teardown method which is called when the bean is unloaded from the container.

83.How can you override beans default lifecycle methods?

The bean tag has two more important attributes with which you can define your own custom initialization and destroy methods. Here I have shown a small demonstration. Two new methods fooSetup and fooTeardown are to be added to your Foo class.
<beans>
   <bean id="bar" class="com.act.Foo" init-method=”fooSetup” destroy=”fooTeardown”/>
</beans>

84.What are Inner Beans?

When wiring beans, if a bean element is embedded to a property tag directly, then that bean is said to the Inner Bean. The drawback of this bean is that it cannot be reused anywhere else.

85.What are the different types of bean injections?

There are two types of bean injections.
i.By setter
ii.By constructor

86.What is Auto wiring?

You can wire the beans as you wish. But spring framework also does this work for you. It can auto wire the related beans together. All you have to do is just set the autowire attribute of bean tag to an autowire type.

  <beans>
      <bean id="bar" class="com.act.Foo" Autowire=”autowire type”/>
  </beans>

87.What are different types of Autowire types?

There are four different types by which autowiring can be done.
 1.byName
 2.byType
 3.constructor
 4.autodetect

88.What are the different types of events related to Listeners?

There are a lot of events related to ApplicationContext of spring framework. All the events are subclasses of org.springframework.context.Application-Event. They are
ContextClosedEvent – This is fired when the context is closed.
ContextRefreshedEvent – This is fired when the context is initialized or refreshed.
RequestHandledEvent – This is fired when the web context handles any request.

89.What is a Pointcut?

A pointcut is something that defines at what joinpoints an advice should be applied. Advices can be applied at any joinpoint that is supported by the AOP framework. These Pointcuts allow you to specify where the advice can be applied.

90.What is an Introduction in AOP?

An introduction allows the user to add new methods or attributes to an existing class. This can then be introduced to an existing class without having to change the structure of the class, but give them the new behavior and state.

91.What is a Target?

A target is the class that is being advised. The class can be a third party class or your own class to which you want to add your own custom behavior. By using the concepts of AOP, the target class is free to center on its major concern, unaware to any advice that is being applied.

92.What is a Proxy?

A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the proxy object are the same.

93.What is meant by Weaving?

The process of applying aspects to a target object to create a new proxy object is called as Weaving. The aspects are woven into the target object at the specified joinpoints.

94.What are the different points where weaving can be applied?

 1.Compile Time
 2.Classload Time
 3.Runtime

95.What are the different types of AutoProxying?

 1.BeanNameAutoProxyCreator
 2.DefaultAdvisorAutoProxyCreator
 3.Metadata autoproxying

96.What is the Exception class related to all the exceptions that are thrown in spring applications?

DataAccessException - org.springframework.dao.DataAccessException
 
97.What kind of exceptions those spring DAO classes throw?

The spring’s DAO class does not throw any technology related exceptions such as SQLException. They throw exceptions which are subclasses of DataAccessException.

98.What is DataAccessException?

DataAccessException is a RuntimeException. This is an Unchecked Exception. The user is not forced to handle these kinds of exceptions.

99.How can you configure a bean to get DataSource from JNDI?

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

100.How can you create a DataSource connection pool?

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driver">
               <value>${db.driver}</value>
         </property>
         <property name="url">
              <value>${db.url}</value>
         </property>
         <property name="username">
             <value>${db.username}</value>
         </property>
         <property name="password">
            <value>${db.password}</value>
         </property>
</bean>

101.How JDBC can be used more efficiently in spring framework?

JDBC can be used more efficiently with the help of a template class provided by spring framework called as JdbcTemplate.

102.How do you write data to backend in spring using JdbcTemplate?

The JdbcTemplate uses several of these callbacks when writing data to the database. The usefulness you will find in each of these interfaces will vary. There are two simple interfaces. One is PreparedStatementCreator and the other interface is BatchPreparedStatementSetter.

103.Explain about PreparedStatementCreator?

PreparedStatementCreator is one of the most common used interfaces for writing data to database. The interface has one method createPreparedStatement().
PreparedStatement createPreparedStatement(Connection conn) throws SQLException;When this interface is implemented, we should create and return a PreparedStatement from the Connection argument, and the exception handling is automatically taken care off. When this interface is implemented, another interface SqlProvider is also implemented which has a method called getSql() which is used to provide sql strings to JdbcTemplate.

104.Explain about BatchPreparedStatementSetter?

If the user what to update more than one row at a shot then he can go for BatchPreparedStatementSetter. This interface provides two methods
setValues(PreparedStatement ps, int i) throws SQLException;
int getBatchSize();
The getBatchSize() tells the JdbcTemplate class how many statements to create. And this also determines how many times setValues() will be called.

105.Explain about RowCallbackHandler and why it is used?

In order to navigate through the records we generally go for ResultSet. But spring provides an interface that handles this entire burden and leaves the user to decide what to do with each row. The interface provided by spring is RowCallbackHandler. There is a method processRow() which needs to be implemented so that it is applicable for each and every row.
void processRow(java.sql.ResultSet rs);

0 comments:

Post a Comment