Why is main()
method static?
|
To access the static
method the object of the class is not needed. The method can be access
directly with the help of ClassName. So when a program is started the JVM
search for the class with main method and calls it without creating an object
of the class.
|
What is the difference between static
methods and instance
methods?
|
Instance method belongs to the instance of a class
therefore it requires an instance before it can be invoked, whereas static
method belongs to the class itself and not to any class instance so it
doesn’t need an instance to be invoked.
Instance methods use dynamic (late) binding, whereas static methods use
static (early) binding.
When the JVM invokes a class instance method, it selects the method to invoke
based on the type of the object reference, which is always known at run-time.
On the other hand, when the JVM invokes a static method, it selects the
method to invoke based on the actual class of the object, which may only be
known at compile time.
|
Can static block throw exception?
|
Yes, static block can throw only Runtime exception or can use a
try-catch block to catch checked exception.
Typically scenario will be if JDBC connection is created in static block and
it fails then exception can be caught, logged and application can exit. If
System.exit() is not done, then application may continue and next time if the
class is referred JVM will throw NoClassDefFounderror since the class was not
loaded by the Classloader.
|
What is difference between
abstract class and interface?
|
1) A class is called abstract
when it contains at least one abstract method. It can also contain n numbers
of concrete method. Interface can
contain only abstract ( non-implemented) methods.
2) The abstract class can have
public, private, protect or default variables and also constants. In interface the variable is by default public final. In nutshell the interface doesn’t have
any variables it only has constants.
3) A class can extend only one abstract class
but a class can implement multiple interfaces.
4) If an interface is implemented it is compulsory to implement all of its
methods but if an abstract class is extended it’s not compulsory to implement
all methods.
5) The problem with an interface is, if you want to
add a new feature (method) in its contract, then you MUST implement that
method in all of the classes which implement that interface. However, in the
case of an abstract class, the method can be simply implemented in the
abstract class and the same can be called by its subclass.
|
Explain with example to describe
when to use abstract class and interface?
|
Consider a scenario where all Cars will have 4 tyres and other
features can be different.
In this case any subclass of Car has to have 4 tyres. This is a case where
abstract class will be used and a default implementation for tyres will be
provided.
public abstract class Car{
public abstract String getCarName();
public final int getNoOfTyres(){
return 4;
}
}
Consider a scenario where Cars can have any number of doors and other
features can also be different. In this case interface will be created.
public interface Car{
public abstract String getCarName();
public abstract int getNoOfDoors();
}
|
Does java support multiple
interitance? Why?
|
Java doesn’t support multiple inheritance but it provide
a way through which it can enact it.
Consider the scenario is C++
Class A{
public void add(){
// some text
}
}
Class B{
public void add(){
// some text
}
}
Class C extends A,B{
public static void main(String arg[]){
C objC = new C();
objC.add(); // problem, compiler gets confused and cant
decide to call Class A or B method.
}
This problem is called Diamond problem.
This problem in java is taken care with the use of interfaces
In Java similar problem would look like:
Interface A{
add();
}
interface B{
add();
}
class C implements A,B{
add(){
// doesnt matter which interface it belong to
}
}
|
Can this
keyword be assigned null value?
|
No
|
What are the different types of references
in java?
|
Java has a more
expressive system of reference than most other garbage-collected programming
languages, which allows for special behavior for garbage collection. A normal
reference in Java is known as a strong reference. The java.lang.ref
package defines three other types of references—soft, weak, and
phantom references. Each type of reference is designed for a specific
use.
A SoftReference can be used to
implement a cache. An object that is not reachable by a strong reference
(that is, not strongly reachable), but is referenced by a soft
reference is called softly reachable. A softly reachable object may be
garbage collected at the discretion of the garbage collector. This generally
means that softly reachable objects will only be garbage collected when free
memory is low, but again, it is at the discretion of the garbage collector.
Semantically, a soft reference means "keep this object unless the memory
is needed."
A WeakReference is used to implement
weak maps. An object that is not strongly or softly reachable, but is
referenced by a weak reference is called weakly reachable. A weakly
reachable object will be garbage collected during the next collection cycle.
This behavior is used in the class java.util.WeakHashMap. A weak map allows
the programmer to put key/value pairs in the map and not worry about the objects
taking up memory when the key is no longer reachable anywhere else. Another
possible application of weak references is the string intern pool.
Semantically, a weak reference means "get rid of this object when
nothing else references it."
A PhantomReference is used to
reference objects that have been marked for garbage collection and have been
finalized, but have not yet been reclaimed. An object that is not strongly,
softly or weakly reachable, but is referenced by a phantom reference is
called phantom reachable. This allows for more flexible cleanup than
is possible with the finalization mechanism alone. Semantically, a phantom
reference means "this object is no longer needed and has been finalized
in preparation for being collected."
|
How to change the heap size of a
JVM?
|
The old generation's default heap size can be overridden by using the
-Xms and -Xmx switches to specify the initial and maximum sizes respectively:
java -Xms -Xmx program
For example:
java -Xms64m -Xmx128m program
|
What is difference between
instanceof and isInstance(Object obj)?
|
Differences are
as follows:
1) instanceof is
a reserved word of Java, but isInstance(Object obj) is a method of
java.lang.Class.
if (obj
instanceof MyType) {
...
}else if (MyType.class.isInstance(obj)) {
...
}
2) instanceof is
used of identify whether the object is type of a particular class or its
subclass but isInstance(obj) is used to identify object of a particular
class.
|
Java supports pass by value or
pass by reference?
|
Java supports
only pass by value. The arguments passed as a parameter to a method is mainly
primitive data types or objects. For the data type the actual value is
passed.
Java passes the references by value just like any other parameter. This means
the references passed to the method are actually copies of the original
references.Java copies and passes the reference by value, not the object.
Thus, method manipulation will alter the objects, since the references point
to the original objects.Consider the example:
public void tricky(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: "
+pnt1.y);
System.out.println("X: " + pnt2.x + " Y: "
+pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" +
pnt1.y);
System.out.println("X: " + pnt2.x + " Y: "
+pnt2.y);
}
OutPut:
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0
The method
successfully alters the value of pnt1, even though it is passed by value;
however, a swap of pnt1 and pnt2 fails! This is the major source of
confusion. In the main() method, pnt1 and pnt2 are nothing more than object
references. When you pass pnt1 and pnt2 to the tricky() method, Java passes
the references by value just like any other parameter. This means the
references passed to the method are actually copies of the original
references.
|
What is memory leak?
|
A memory leak is where an unreferenced object that
will never be used again still hangs around in memory and doesnt get garbage
collected.
|
What is the difference between
equals() and ==?
|
== operator is
used to compare the references of the objects.
public bollean equals(Object o) is the method provided by the Object
class. The default implementation uses == operator to compare two objects.
But since the method can be overridden like for String class. equals ()
method can be used to compare the values of two objects.
String str1 = "MyName";
String str2 = "MyName";
String str3 = str2;
if(str1 == str2){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
if(str1.equals(str2)){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
Output:
Objects are not equal
Objects are equal
String str2 = "MyName";
String str3 = str2;
if(str2 == str3){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
if(str3.equals(str2)){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
OutPut:
Objects are equal
Objects are equal
|
How to make sure that Childclass
method actually overrides the method of the superclass?
|
The @Override annotation can be added to the javadoc
for the new method. If you accidently miss an argument or capitalize the
method name wrong, the compiler will generate a compile-time error.
|
How to find the size of an
object?
|
The heap size of
an object can be found using -
Runtime.totalMemory()-Runtime.freeMemory() .
|
Spring Questions
|
|
Explain DI or IOC pattern
|
Dependency injection is a way to achieve loose coupling. Inversion of
control (IOC) relates to the way in which an object obtains references to its
dependencies. This is often done by a lookup method. The advantage of
inversion of control is that it decouples objects from specific lookup
mechanisms and implementations of the objects it depends on. As a result,
more flexibility is obtained for production applications as well as for
testing.
Dependency injection (DI) is a programming design pattern and architectural
model, sometimes also referred to as inversion of control or IOC, although
technically speaking, dependency injection specifically refers to an
implementation of a particular form of IOC. Dependency Injection describes
the situation where one object uses a second object to provide a particular
capacity. For example, being passed a database connection as an argument to
the constructor method instead of creating one inside the constructor. The
term "Dependency injection" is a misnomer, since it is not a
dependency that is injected; rather it is a provider of some capability or
resource that is injected. There are three common forms of dependency
injection: setter, constructor and interface-based injection.
|
What are the advantages of
spring framework?
|
Spring has layered architecture. Use what you need
and leave you don't need.
Spring Enables POJO Programming. There is no behind the scene magic here.
POJO programming enables continuous integration and testability.
Dependency Injection and Inversion of Control Simplifies JDBC
Open source and no vendor lock-in.
|
Explain BeanFactory in
spring
|
Bean factory is an implementation of the factory design pattern and
its function is to create and dispense beans. As the bean factory knows about
many objects within an application, it is able to create association between
collaborating objects as they are instantiated. This removes the burden of
configuration from the bean and the client. There are several implementation
of BeanFactory. The most useful one is
"org.springframework.beans.factory.xml.XmlBeanFactory" It loads its
beans based on the definition contained in an XML file. To create an
XmlBeanFactory, pass a InputStream to the constructor. The resource will
provide the XML to the factory.
BeanFactory factory = new XmlBeanFactory(new
FileInputStream("myBean.xml"));
This line tells the bean factory to read the bean definition from the XML
file. The bean definition includes the description of beans and their
properties. But the bean factory doesn't instantiate the bean yet. To
retrieve a bean from a 'BeanFactory', the getBean() method is called. When getBean()
method is called, factory will instantiate the bean and begin setting the
bean's properties using dependency injection.
myBean bean1 = (myBean)factory.getBean("myBean");
|
Explain the role of
ApplicationContext in spring
|
While Bean Factory is used for simple applications;
the Application Context is spring's more advanced container. Like
'BeanFactory' it can be used to load bean definitions, wire beans together
and dispense beans upon request. It also provide
1) A means for resolving text messages, including support for
internationalization.
2) A generic way to load file resources.
3) Events to beans that are registered as listeners.
Because of additional functionality, 'Application Context' is preferred over
a BeanFactory. Only when the resource is scarce like mobile devices,
'BeanFactory' is used. The three commonly used implementation of 'Application
Context' are
1. ClassPathXmlApplicationContext : It Loads context definition from an XML
file located in the classpath, treating context definitions as classpath
resources. The application context is loaded from the application's classpath
by using the code
ApplicationContext context = new
ClassPathXmlApplicationContext("bean.xml");
2. FileSystemXmlApplicationContext : It loads context definition from an XML
file in the filesystem. The application context is loaded from the file
system by using the code
ApplicationContext context = new
FileSystemXmlApplicationContext("bean.xml");
|
What is AOP? How does it
relate with IOC? What are different tools to utilize AOP?
|
Aspect-oriented programming, or AOP, is a programming technique that
allows programmers to modularize crosscutting concerns, or behaviour that
cuts across the typical divisions of responsibility, such as logging and
transaction management. The core construct of AOP is the aspect, which
encapsulates behaviours affecting multiple classes into reusable modules. AOP
and IOC are complementary technologies in that both apply a modular approach
to complex problems in enterprise application development. In a typical
object-oriented development approach you might implement logging
functionality by putting logger statements in all your methods and Java
classes. In an AOP approach you would instead modularize the logging services
and apply them declaratively to the components that required logging. The
advantage, of course, is that the Java class doesn't need to know about the
existence of the logging service or concern itself with any related code. As
a result, application code written using Spring AOP is loosely coupled. The
best tool to utilize AOP to its capability is AspectJ. However AspectJ works
at the byte code level and you need to use AspectJ compiler to get the aop
features built into your compiled code. Nevertheless AOP functionality is
fully integrated into the Spring context for transaction management, logging,
and various other features. In general any AOP framework control aspects in
three possible ways:
Joinpoints: Points in a program's execution. For example, joinpoints could
define calls to specific methods in a class
Pointcuts: Program constructs to designate joinpoints and collect specific
context at those points
Advices: Code that runs upon meeting certain conditions. For example, an
advice could log a message before executing a joinpoint
|
What is spring? What are
the various parts of spring framework? What are the different persistence
frameworks which could be used with spring?
|
Spring is an open source framework created to
address the complexity of enterprise application development. One of the
chief advantages of the Spring framework is its layered architecture, which
allows you to be selective about which of its components you use while also
providing a cohesive framework for J2EE application development. The Spring
modules are built on top of the core container, which defines how beans are
created, configured, and managed. Each of the modules (or components) that
comprise the Spring framework can stand on its own or be implemented jointly
with one or more of the others. The functionality of each component is as
follows:
The core container: The core container provides the essential functionality
of the Spring framework. A primary component of the core container is the
BeanFactory, an implementation of the Factory pattern. The BeanFactory
applies the Inversion of Control (IOC) pattern to separate an application’s
configuration and dependency specification from the actual application code.
Spring context: The Spring context is a configuration file that provides
context information to the Spring framework. The Spring context includes
enterprise services such as JNDI, EJB, e-mail, internalization, validation,
and scheduling functionality.
Spring AOP: The Spring AOP module integrates aspect-oriented programming
functionality directly into the Spring framework, through its configuration
management feature. As a result you can easily AOP-enable any object managed
by the Spring framework. The Spring AOP module provides transaction
management services for objects in any Spring-based application. With Spring
AOP you can incorporate declarative transaction management into your
applications without relying on EJB components.
Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful
exception hierarchy for managing the exception handling and error messages
thrown by different database vendors. The exception hierarchy simplifies
error handling and greatly reduces the amount of exception code you need to
write, such as opening and closing connections. Spring DAO’s JDBC-oriented
exceptions comply to its generic DAO exception hierarchy.
Spring ORM: The Spring framework plugs into several ORM frameworks to provide
its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps.
All of these comply to Spring’s generic transaction and DAO exception
hierarchies.
Spring Web module: The Web context module builds on top of the application
context module, providing contexts for Web-based applications. As a result,
the Spring framework supports integration with Jakarta Struts. The Web module
also eases the tasks of handling multi-part requests and binding request
parameters to domain objects.
Spring MVC framework: The Model-View-Controller (MVC) framework is a
full-featured MVC implementation for building Web applications. The MVC
framework is highly configurable via strategy interfaces and accommodates
numerous view technologies including JSP, Velocity, Tiles, iText, and POI.
|
Explain the role of
ApplicationContext in spring.
|
While Bean Factory is used for simple applications; the Application
Context is spring's more advanced container. Like 'BeanFactory' it can be
used to load bean definitions, wire beans together and dispense beans upon
request. It also provide
1) A means for resolving text messages, including support for
internationalization.
2) A generic way to load file resources.
3) Events to beans that are registered as listeners.
Because of additional functionality, 'Application Context' is preferred over
a BeanFactory. Only when the resource is scarce like mobile devices,
'BeanFactory' is used. The three commonly used implementation of 'Application
Context' are
1. ClassPathXmlApplicationContext : It Loads context definition from an XML
file located in the classpath, treating context definitions as classpath
resources. The application context is loaded from the application's classpath
by using the code
ApplicationContext context = new
ClassPathXmlApplicationContext("bean.xml");
2. FileSystemXmlApplicationContext : It loads context definition from an XML
file in the filesystem. The application context is loaded from the file
system by using the code
ApplicationContext context = new
FileSystemXmlApplicationContext("bean.xml");
3. XmlWebApplicationContext : It loads context definition from an XML file
contained within a web application.
|
How
does Spring supports DAO in hibernate?
|
Spring’s
HibernateDaoSupport class is a convenient super class for Hibernate DAOs. It
has handy methods you can call to get a Hibernate Session, or a
SessionFactory. The most convenient method is getHibernateTemplate(), which
returns a HibernateTemplate. This template wraps Hibernate checked exceptions
with runtime exceptions, allowing your DAO interfaces to be Hibernate
exception-free.
Example:
public class UserDAOHibernate extends
HibernateDaoSupport {
public User getUser(Long id) {
return (User) getHibernateTemplate().get(User.class,
id);
}
public void saveUser(User user) {
getHibernateTemplate().saveOrUpdate(user);
if (log.isDebugEnabled()) {
log.debug(“userId set to: “ + user.getID());
}
}
public void removeUser(Long id) {
Object user =
getHibernateTemplate().load(User.class, id);
getHibernateTemplate().delete(user);
}
}
|
What
are the id generator classes in hibernate?
|
increment: It
generates identifiers of type long, short or int that are unique only when no
other process is inserting data into the same table. It should not the used
in the clustered environment.
identity: It supports identity columns in DB2,
MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of
type long, short or int.
sequence: The sequence generator uses a sequence
in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The
returned identifier is of type long, short or int
hilo: The hilo generator uses a hi/lo algorithm
to efficiently generate identifiers of type long, short or int, given a table
and column (by default hibernate_unique_key and next_hi respectively) as a
source of hi values. The hi/lo algorithm generates identifiers that are
unique only for a particular database. Do not use this generator with
connections enlisted with JTA or with a user-supplied connection.
seqhilo: The seqhilo generator uses a hi/lo
algorithm to efficiently generate identifiers of type long, short or int,
given a named database sequence.
uuid: The uuid generator uses a 128-bit UUID
algorithm to generate identifiers of type string, unique within a network
(the IP address is used). The UUID is encoded as a string of hexadecimal
digits of length 32.
guid: It uses a database-generated GUID string on
MS SQL Server and MySQL.
native: It picks identity, sequence or hilo
depending upon the capabilities of the underlying database.
assigned: lets the application to assign an
identifier to the object before save() is called. This is the default
strategy if no element is specified.
select: retrieves a primary key assigned by a
database trigger by selecting the row by some unique key and retrieving the
primary key value.
foreign: uses the identifier of another
associated object. Usually used in conjunction with a primary key
association.
|
How
is a typical spring implementation look like?
|
For
a typical Spring Application we need the following files
1. An interface that defines the functions.
2. An Implementation that contains properties,
its setter and getter methods, functions etc.,
3. A XML file called Spring configuration file.
4. Client program that uses the function.
|
How
do you define hibernate mapping file in spring?
|
Add the
hibernate mapping file entry in mapping resource inside Spring’s
applicationContext.xml file in the web/WEB-INF directory.
< property name="mappingResources"
>
< list >
< value > org/appfuse/model/User.hbm.xml
< / value >
< / list >
< / property >
|
How
do you configure spring in a web application?
|
At
the very least, you can simply add Spring’s ContextLoaderListener to your
web.xml file:
< listener >
< listener-class >
org.springframework.web.context.ContextLoaderListener < / listener-class
>
< / listener >
|
Can
you have xyz.xml file instead of applicationcontext.xml?
|
ContextLoaderListener
is a ServletContextListener that initializes when your webapp starts up. By
default, it looks for Spring’s configuration file at
WEB-INF/applicationContext.xml. You can change this default value by
specifying a element named “contextConfigLocation.” Example:
< listener >
< listener-class >
org.springframework.web.context.ContextLoaderListener
< context-param >
< param-name > contextConfigLocation <
/ param-name >
< param-value > /WEB-INF/xyz.xml< /
param-value >
< / context-param >
< / listener-class >
< / listener >
|
How
do you configure your database driver in spring?
|
Using
datasource
"org.springframework.jdbc.datasource.DriverManagerDataSource".
Example:
< bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
>
< property name="driverClassName"
>
< value > org.hsqldb.jdbcDriver < /
value >
< / property >
< property name="url" >
< value > jdbc:hsqldb:db/appfuse < /
value >
< / property >
< property name="username" >
< value > sa < / value > < / property >
< property name="password" >
< value > < / value > < / property >
< / bean >
|
How
can you configure JNDI instead of datasource in spring
applicationcontext.xml?
|
Using "org.springframework.jndi.JndiObjectFactoryBean".
Example:
< bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean" >
< property name="jndiName" >
< value > java:comp/env/jdbc/appfuse <
/ value >
< / property >
< / bean >
|
What
are the key benefits of Hibernate?
|
These
are the key benifits of Hibernate:
Transparent persistence based on POJOs without
byte code processing
Powerful object-oriented hibernate query
language
Descriptive O/R Mapping through mapping file.
Automatic primary key generation
Hibernate cache: Session Level, Query and Second
level cache.
Performance: Lazy initialization, Outer join
fetching, Batch fetching
|
What
is hibernate session and session factory? How do you configure sessionfactory
in spring configuration file?
|
Hibernate
Session is the main runtime interface between a Java application and
Hibernate. SessionFactory allows applications to create hibernate session by
reading hibernate configurations file hibernate.cfg.xml.
// Initialize the Hibernate environment
Configuration cfg = new
Configuration().configure();
// Create the session factory
SessionFactory factory =
cfg.buildSessionFactory();
// Obtain the new session object
Session session = factory.openSession();
The call to Configuration().configure() loads
the hibernate.cfg.xml configuration file and initializes the Hibernate
environment. Once the configuration is initialized, you can make any
additional modifications you desire programmatically. However, you must make
these modifications prior to creating the SessionFactory instance. An
instance of SessionFactory is typically created once and used to create all
sessions related to a given context.
The main function of the Session is to offer
create, read and delete operations for instances of mapped entity classes.
Instances may exist in one of three states:
transient: never persistent, not associated with
any Session
persistent: associated with a unique Session
detached: previously persistent, not associated
with any Session
A Hibernate Session object represents a single
unit-of-work for a given data store and is opened by a SessionFactory
instance. You must close Sessions when all work for a transaction is
completed. The following illustrates a typical Hibernate session:
Session session = null;
UserInfo user = null;
Transaction tx = null;
try {
session = factory.openSession();
tx = session.beginTransaction();
user = (UserInfo)session.load(UserInfo.class,
id);
tx.commit();
} catch(Exception e) {
if (tx != null) {
try {
tx.rollback();
} catch (HibernateException e1) {
throw new DAOException(e1.toString()); }
} throw new DAOException(e.toString());
} finally {
if (session != null) {
try {
session.close();
} catch (HibernateException e) { }
}
}
|
What
is the difference between hibernate get and load methods?
|
The
load() method is older; get() was added to Hibernate’s API due to user
request. The difference is trivial:
The following Hibernate code snippet retrieves a
User object from the database:
User user = (User) session.get(User.class,
userID);
The get() method is special because the
identifier uniquely identifies a single instance of a class. Hence it’s
common for applications to use the identifier as a convenient handle to a
persistent object. Retrieval by identifier can use the cache when retrieving
an object, avoiding a database hit if the object is already cached.
Hibernate also provides a load() method:
User user = (User) session.load(User.class,
userID);
If load() can’t find the object in the cache or
database, an exception is thrown. The load() method never returns null. The
get() method returns
null if the object can’t be found. The load()
method may return a proxy instead of a real persistent instance. A proxy is a
placeholder instance of a runtime-generated subclass (through cglib or
Javassist) of a mapped persistent class, it can initialize itself if any
method is called that is not the mapped database identifier getter-method. On
the other hand, get() never returns a proxy. Choosing between get() and
load() is easy: If you’re certain the persistent object exists, and
nonexistence would be considered exceptional, load() is a good option. If you
aren’t certain there is a persistent instance with the given identifier, use
get() and test the return value to see if it’s null. Using load() has a
further implication: The application may retrieve a valid reference (a proxy)
to a persistent instance without hitting the database to retrieve its
persistent state. So load() might not throw an exception when it doesn’t find
the persistent object in the cache or database; the exception would be thrown
later, when the proxy is accessed.
|
What
type of transaction management is supported in hibernate?
|
Hibernate
communicates with the database via a JDBC Connection; hence it must support
both managed and non-managed transactions.
Non-managed in web containers:
< bean id="transactionManager"
class="org.springframework.orm.hibernate.HibernateTransactionManager"
>
< property name="sessionFactory"
>
< ref local="sessionFactory" / >
< / property >
< / bean >
Managed in application server using JTA:
< bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager."
>
< property name="sessionFactory"
>
< ref local="sessionFactory" / >
< / property >
< / bean >
|
What
is lazy loading and how do you achieve that in hibernate?
|
Lazy
setting decides whether to load child objects while loading the Parent
Object. You need to specify parent class.Lazy = true in hibernate mapping
file. By default the lazy loading of the child objects is true. This make
sure that the child objects are not loaded unless they are explicitly invoked
in the application by calling getChild() method on parent. In this case hibernate
issues a fresh database call to load the child when getChild() is actually
called on the Parent object. But in some cases you do need to load the child
objects when parent is loaded. Just make the lazy=false and hibernate will
load the child when parent is loaded from the database. Examples: Address
child of User class can be made lazy if it is not required frequently. But
you may need to load the Author object for Book parent whenever you deal with
the book for online bookshop.
Hibernate does not support lazy initialization
for detached objects. Access to a lazy association outside of the context of
an open Hibernate session will result in an exception.
|
What
are the different fetching strategies in Hibernate?
|
Hibernate3
defines the following fetching strategies:
Join fetching - Hibernate retrieves the
associated instance or collection in the same SELECT, using an OUTER JOIN.
Select fetching - a second SELECT is used to
retrieve the associated entity or collection. Unless you explicitly disable lazy
fetching by specifying lazy="false", this second select will only
be executed when you actually access the association.
Subselect fetching - a second SELECT is used to
retrieve the associated collections for all entities retrieved in a previous
query or fetch. Unless you explicitly disable lazy fetching by specifying
lazy="false", this second select will only be executed when you
actually access the association.
Batch fetching - an optimization strategy for
select fetching - Hibernate retrieves a batch of entity instances or
collections in a single SELECT, by specifying a list of primary keys or
foreign keys.
|
What
are different types of cache hibernate supports?
|
Caching
is widely used for optimizing database applications. 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 Session Factory 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. To reduce
database traffic, second-level cache keeps loaded objects at the Session
Factory level between transactions. These objects are available to the whole
application, not just to the user running the query. This way, each time a
query returns an object that is already loaded in the cache, one or more
database transactions potentially are avoided. In addition, you can use a
query-level cache if you need to cache actual query results, rather than just
persistent objects. The query cache should always be used in conjunction with
the second-level cache. Hibernate supports the following open-source cache
implementations out-of-the-box:
EHCache is a fast, lightweight, and easy-to-use
in-process cache. It supports read-only and read/write caching, and memory
and disk-based caching. However, it does not support clustering.
OSCache is another open-source caching solution.
It is part of a larger package, which also provides caching functionalities
for JSP pages or arbitrary objects. It is a powerful and flexible package,
which, like EHCache, supports read-only and read/write caching, and memory-
and disk-based caching. It also provides basic support for clustering via
either JavaGroups or JMS.
SwarmCache is a simple cluster-based caching
solution based on JavaGroups. It supports read-only or nonstrict read/write
caching (the next section explains this term). This type of cache is
appropriate for applications that typically have many more read operations
than write operations.
JBoss TreeCache is a powerful replicated
(synchronous or asynchronous) and transactional cache. Use this solution if
you really need a true transaction-capable caching architecture.
Commercial Tangosol Coherence cache.
|
What
are the different caching strategies?
|
The following
four caching strategies are available:
Read-only: This strategy is useful for data that
is read frequently but never updated. This is by far the simplest and
best-performing cache strategy.
Read/write: Read/write caches may be appropriate
if your data needs to be updated. They carry more overhead than read-only
caches. In non-JTA environments, each transaction should be completed when
Session.close() or Session.disconnect() is called.
Nonstrict read/write: This strategy does not
guarantee that two transactions won't simultaneously modify the same data.
Therefore, it may be most appropriate for data that is read often but only
occasionally modified.
Transactional: This is a fully transactional
cache that may be used only in a JTA environment.
|
How
do you configure 2nd level cache in hibernate?
|
To
activate second-level caching, you need to define the
hibernate.cache.provider_class property in the hibernate.cfg.xml file as
follows:
< hibernate-configuration >
< session-factory >
< property
name="hibernate.cache.provider_class"
>org.hibernate.cache.EHCacheProvider< / property >
< / session-factory >
< / hibernate-configuration >
By default, the second-level cache is activated
and uses the EHCache provider.
To use the query cache you must first enable it
by setting the property hibernate.cache.use_query_cache to true in
hibernate.properties.
|
What
is the difference between sorted and ordered collection in hibernate?
|
A sorted
collection is sorted in-memory using java comparator, while order collection
is ordered at the database level using order by clause.
|
What
are the types of inheritance models and describe how they work like vertical
inheritance and horizontal?
|
There
are three types of inheritance mapping in hibernate:
Example: Let us take the simple example of 3
java classes. Class Manager and Worker are inherited from Employee Abstract
class.
1. Table per concrete class with unions: In this
case there will be 2 tables. Tables: Manager, Worker [all common attributes
will be duplicated]
2. Table per class hierarchy: Single Table can
be mapped to a class hierarchy. There will be only one table in database
called 'Employee' that will represent all the attributes required for all 3
classes. But it needs some discriminating column to differentiate between
Manager and worker;
3. Table per subclass: In this case there will
be 3 tables represent Employee, Manager and Worker
|
Differentiate between BeanFactory
and ApplicationContext in spring.
|
- With ApplicationContext more than one config files are possible
while only one config file or .xml file is possible with BeanFactory.
- ApplicationContext publishes events to beans that are registered as
listeners while BeanFactory doesn't support this
- ApplicationContext support internationalization messages, application
life-cycle events, validation and many enterprise services like JNDI access,
EJB integration, remoting etc. while BeanFactory doesn't support any of
these.
|
What is the difference between
singleton and prototype bean?
|
Mainly it is the scope of a beans which defines
their existence on the application
- Singleton: It means single bean definition to a single object instance per
Spring IOC container.
- Prototype: It means a single bean definition to any number of object
instances.
3
|
How do beans become 'singleton' or
prototype?
|
- There exists an
attribute in bean tag, called 'singleton’.
- If it is marked 'true', the bean becomes singleton.
- If it is marked 'false', the bean becomes prototype.
|
What type of transaction Management
Spring support?
|
Spring supports two types of transaction management:
1. Programmatic transaction management
2. Declarative transaction management.
|
When do you use programmatic and
declarative transaction management ?
|
- Programmatic transaction management is used preferably when you have
a small number of transactional operations.
- Incase of large number of transactional operations it is better to use
declarative transaction management.
|
What is IOC?
|
- IOC stands for Inversion of Control pattern.
- It is also called as dependency injection.
- This concept says that you do not create your objects but describe how they
should be created.
- Similarly, you do not directly connect your components and services
together in code but describe which services are needed by which components
in a configuration file.
- A container then hooks them all up.
|
What are the different types of IoC
(dependency injection) ?
|
There are three types of dependency injection:
a.) Constructor Injection : Here dependencies are provided as constructor
parameters.
b.) Setter Injection : Dependencies are assigned through JavaBeans
properties.
c.) Interface Injection : Injection is performed through an interface.
Spring supports only first two categories of Injection.
|
What are the benefits of IOC?
|
The main benefits of IOC or dependency injection are:
a.) It minimizes the amount of code in your application.
b.) It makes your application easy to test as it doesn't require any
singletons or JNDI lookup mechanisms in your unit test cases.
c.) Loose coupling is promoted with minimal effort and least intrusive
mechanism.
d.) IOC containers support eager instantiation and lazy loading of services.
|
What is Bean Wiring ?
|
Bean wiring means creating associations between application components
i.e. beans within the spring container.
|
How do you access Hibernate using
Spring ?
|
There are two ways to Spring’s Hibernate integration:
a.) By Inversion of Control with a HibernateTemplate and Callback
b.) By extending HibernateDaoSupport and Applying an AOP Interceptor
|
How would you integrate Spring and
Hibernate using HibernateDaoSupport?
|
This can be done through Spring’s SessionFactory called
LocalSessionFactory. The steps in integration process are:
a.) Configure the Hibernate SessionFactory
b.) Extend your DAO Implementation from HibernateDaoSupport
c.) Wire in Transaction Support with AOP
|
What are the various transaction
manager implementations in Spring ?
|
1. DataSourceTransactionManager : PlatformTransactionManager
implementation for single JDBC data sources.
2. HibernateTransactionManager: PlatformTransactionManager implementation for
single Hibernate session factories.
3. JdoTransactionManager : PlatformTransactionManager implementation for
single JDO persistence manager factories.
4. JtaTransactionManager : PlatformTransactionManager implementation for JTA,
i.e. J2EE container transactions.
|
What
is Spring?
|
Spring is a framework that resolves common problems in JEE
architecture. Managing business objects and encouraging practices such as
programming interfaces rather than classes is a consistent way of using
Spring. Spring addresses all architectural tiers with basic building block by
utilizing IoC. Unique data access abstraction including abstraction of JDBC
framework improves the productivity and reduces the errors using Spring. A
flexible and powerful MVC framework which is integrated into the overall IoC
container.
Spring is an opensource lightweight looslycoupled aspect oriented and
dependency injection(inversion of control) based java-jee framework to
develop all kinds of java, jee applications.
|
What
are the Core container module and Application context module?
|
Core
Container Module: This module is the fundamental module of spring
framework. For a spring-based application, BeanFactory is the core. The
Spring framework was developed on top of this module. Spring container is
made by this module.
Application
Context Module: Spring is called a framework because of this
module. The concept of BeanFactory is used to extend this module to provide
support for internationalization (I18N) messages etc. Enterprise services
such as JNDI,EJB integration, remoting and scheduling are supplied by this
module.
|
Explain
Bean lifecycle in Spring framework.
|
1. The spring
container finds the bean’s definition from the XML file and instantiates the
bean.
2. Using the dependency injection, spring populates all of the properties as
specified in the bean definition.
3. If the bean implements the BeanNameAware interface, the factory calls
setBeanName() passing the bean’s ID.
4. If the bean implements the BeanFactoryAware interface, the factory calls
setBeanFactory(), passing an instance of itself.
5. If there are any BeanPostProcessors associated with the bean, their post-
ProcessBeforeInitialization() methods will be called.
6. If an init-method is specified for the bean, it will be called.
7. Finally, if there are any BeanPostProcessors associated with the bean,
their postProcessAfterInitialization() methods will be called.
|
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.
|
Explain
how to add a bean in spring application.
|
In the bean tag
the id attribute specifies the bean name and the class attribute specifies
the fully qualified class name.
|
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.
|
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.
|
What
is Auto wiring? What are different types of Autowire types?
|
It is possible to automatic resolve collaborators (other beans) for
your bean by inspecting the contents of the BeanFactory.
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.
There are four different types by which auto wiring can be done.
- byName
- byType
- constructor
- autodetect
|
What
is meant by Weaving? What are the different points where weaving can be
applied?
|
In Spring AOP makes it possible to modularize and separate logging,
transaction like services and apply them declaratively to the components
Hence programmer can focus on specific concerns. Aspects are wired into
objects in the spring XML file in the way as JavaBean. This process is known
as '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.
- Compile Time
- Classload Time
- Runtime
|
Explain
the different types of AutoProxying.
|
BeanNameAutoProxyCreator: This proxy is
used to identify beans to proxy through a list of names. It checks the
matches that are direct, “xxx” and “*xxx”.
DefaultAdvisorAutoProxyCreator: This proxy is the
implementation of BeanPostProcessor which creates AOP proxies. These AOP
proxies are based on BeanFactory’s all Candidate Advisors. It is a generic
class which does not have a specific code to handle any specific aspects.
Metadata
autoproxying: The metadata autoproxy is concerned with the
possibility to employ annotations in certain classes, like defining
transactions. To configure this type of proxies, the source level metadata
interpretation and the bean usage that employs those attributes is done by
DefaultAdvisorAutoProxyCreator.
|
What
is DataAccessException?
|
DataAccessException
is an unchecked RuntimeException. These type of exceptions are unforced by
users to handle. This exception is used to handle the errors occurring when
the details of the database access API in use, such as JDBC.
|
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.
|
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.
|
Explain
about RowCallbackHandler and why it is used.
|
n 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 everyrow.
void processRow(java.sql.ResultSet rs);
|
What are the
functionalities provided by the context package to enhance the BeanFactory
functionality?
|
The
functionalities provided by context package are as follows:
1. message access in i18n-style, through the MessageSource interface.
2. Resources access such as URLs and files, through which, the ResourceLoader
interface, can be accessed and used.
3. Publication of events, through the beans that allow, implementing the
ApplicationListener interface. It is done through the use, of the
ApplicationEventPublisher interface.
4. Multiple loading contexts, allowing each to be focused on one particular
layer, such as the web layer of an application, through the HierarchicalBeanFactory
interface.
|
How can you achieve
Internationalization using MessageSource?
|
Internationnalization using message source can be achieved by the
following:
1>String get Mesage(String code, Objct[] args, String default, Local
loc): The basic method used for retrieving a message from the MessageSource.
When no message is to be
found for the specified locale, the default message is used.
2> String getMessage(String code, Objct[] args, Locale loc): Essentially
the
same as the last method, but with a difference: no default message is
specified; if the
message cannot be found, a NoSuchMessageException is shown.
3> String getMessage(MessageSourceResolvable resolvable, Local locale):
properties used for the preceding methods are also wrapped in a class named
MessageSourceResolvable, which you can use with this method.
|
Enlist and explain the
main methods associated with the Resource interface.
|
Methods
associated with resource interface are as follows:
1> getInputStream(): it locates and opens the resource, returning an
InputStream to read from
the resource.
2> exists(): returns a boolean which indicates whether this resource
actually exists in physical form.
3> isOpen(): returns a boolean which indicates whether this resource
represents a handle with an open
stream.
4> getDescription(): returns a description for this resource, which is
used for error output when
working with the resource.
|
Give some examples
where property editing is used in spring.
|
Following are examples for property editing in spring
1> setting of properties on beans is done by using PropertyEditors. To
mention
java.lang.string as the value for a property of some bean you're declaring in
XML file, Spring will use the ClassEditor to try resolving the parameter to a
Class object.
2> passing HTTP request parameters in Spring's MVC framework can be done
using all kinds of PropertyEditors that can be manually bind in all
subclasses of the CommandController.
|
Explain the main AOP
concepts and terminology
|
The main
AOP concepts are as follows:
1> Aspect: a modularization of a concern that cuts through multiple
classes.
2> Join point: is a point during which the execution of a programming,
such as the execution of method or handling of an exception.
3> Advice: action taken by an aspect for a particular join point.
4> Point cut: a predicate that is matched to join points.
5> Introduction: declaration of additional methods or fields on behalf of
a type.
6> Target object: object which is advised by one or more aspects.
7> AOP proxy: an object which is created by AOP framework for implementing
the aspect contracts.
8> Weaving: linking of aspects with other application types or objects to
create an advised object.
|
How can you use spring
to resolve collaborators for your bean? Also state the advantages of auto
wiring?
|
The spring can be used to resolve collaborators automatically by
inspecting contents of the
ApplicationContext.
The Autowiring has the following advantages in spring:
1. Reduces requirement for specifying properties or construction arguments.
2. Updates configuration while evolving of objects.
To understand this lets consider an example: modifying would not be required
in configuration of a dependency while adding it to a class.
3. Switching to explicit wiring when code base is stable can be neglected.
|
List the limitations
of auto wiring.
|
Autowiring
has the following limitations:
1. Overriding and auto wiring are caused due to dependency in property and
constructor argument setting.
2. Less precise as compared to explicit wiring.
3. Tools that generate documentation using a spring might not have access to
wiring information.
4. There is a possibility of clash between bean definitions and argument or
method to be wired.
The problem does not occur much in case of maps, arrays and collection and
cannot be resolved randomly for dependencies which expect one value.
|
In scenarios where you
have to avoid using auto wiring, what are the other options that can be
explored to achieve the same.
|
In
scenarios where using autowiring is prohibited, the following replacements
can achive the same:
1. Abandon autowiring for favor of explicit wiring.
2. Avoid autowiring for a bean definition by setting the autowire-candidate
for attributes to false as described in the next section.
3. Set a single bean definition as the primary candidate by setting the
primary attribute of its
element to true.
4. When Java 5 or later is used, implementation needs more fine-grained
control available with
annotation-based configuration.
|
How do you call the
multiple lifecycle mechanisms configured for the same bean?
|
Multiple lifecycle
mechanisms which are configured for the same bean, with different
initialization methods, are called by the following ways :
1. Methods annotated with use of @PostConstruct
2. afterPropertiesSet() as stated by the InitializingBean callback interface
3. Custom configuration init() method
Destroy methods are called in the same order as follows :
1. Methods annotated with use of @PreDestroy
2. destroy() as stated by the DisposableBean callback interface
3. destroy() method with custom configuration
|
What are the methods
associated with the FactoryBean interface?
|
Following are the methods associated with factory bean interface:
1> Object getObject(): this returns an instance of the object which the
factory creates. This instance can
possibly be shared, depending on the factory returns singletons or
prototypes.
2> boolean isSingleton(): this returns true if this FactoryBean returns
singletons, false
otherwise.
3> Class getObjectType(): this returns the object type returned by the
getObject() method or
null if the type is unknown in advance.
|
What are the
annotations supported by the spring framework?
|
Due to
addition of some core features from the JavaConfig project to the Spring
Framework,the following annotations are now directly supported:
• @Configuration
• @Bean
• @DependsOn
• @Primary
• @Lazy
• @Import
• @ImportResource
• @Value
|
Explain in brief the
metadata contained in the BeanDefinition objects
|
Bean definitions contain the following metadata:
1. A package-qualified class name: which is the actual implementation class
of the bean being defined.
2. Bean behavioral configuration elements, which state the procedure for how
the bean should behave in the container
3. References to other beans that are required for the bean to do its work;
these references are also called collaborators or dependencies.
4. Other configuration settings to set when a new object is created, for
example, the number of connections to use in a bean that manages a connection
pool or the size limit of the pool.
|
What are the different
properties the metadata translates into to make up the bean definition?
|
Metadata
translates into the following properties to make up
1. Property defined in class the section called “Instantiating beans”
2. Property defined in name the section called “Naming beans” scope
constructor arguments the section known as “Dependency injection”
3. Properties the section known as “Dependency injection” auto wiring mode
the section known as “Autowiring collaborators”
4. lazy-initialization mode the section called “Lazy-initialized beans”
5. Initialization method the section called “Initialization callbacks”
6. Destruction method the section called “Destruction callbacks”
|
Briefly describe the 2
ways in which the class property can be used.
|
The class property can be put to use in the following ways:
1. It is used to specify the java bean for class to be constructed when
container directly creates java bean by calling constructor reflectively.
This procedure is also used for java code which uses a new operator.
2. It is also used to specify the class which contains static factory method
which is invoked for creating object. Another case in this which doesn’t
occur much is when static factory method is invoked by container on a class
for creating the bean.
|
Explain the dependency
resolution process
|
The
dependency resolution process is carried out as follows:
1. Creation an initialization of application text inside configuration
metadata( can be specified in XML, java code,annotations) is done. This
describes all the beans.
2. For each bean, its dependency is expressed in the form of properties,
constructor arguments, or
arguments to the static-factory method if that is used instead of a normal
constructor.
3. Each property or constructor argument is actual definition of the value
which belong to set, or a reference to another bean which is in the
container.
4. Each property or constructor argument which is a value is gone through
conversion from its specified format to the actual type of that property or
constructor argument.
|
Give examples of how
spring platform can be used by an application developer.
|
The spring platform can be used by an application developer in the
following way ::
• Java method can be made to execute in a database transaction without having
to deal with transaction APIs.
• Local Java method can be made a remote procedure without having to deal
with remote APIs.
• Local Java method can be made a management operation without having to deal
with JMX APIs.
• Local Java method can be made a message handler without having to deal with
JMS APIs.
|
What are the various
ways of using spring?
|
There are
various ways and forms in which springs can be used.
They are listed as follows:
1. Full-fledged Spring web app
2. Spring middle-tier provides help of a third-party web framework
3. Remote usage scenario: allow the system to be used to remotely use the
resources from the server. The remote usage can be done to grab the data from
the server or for troubleshooting the environment.
4. EJB -- Wrapping existing POJOs
|
Specify the locations
where spring can publish its artifacts.
|
Spring generally publishes its artifacts to four different places:
1. Community download site http://www.springsource.org/downloads/community.
2. Maven Central, which is considered the default repository that Maven
queries, and does not require any special configuration to use.
3. The Enterprise Bundle Repository (EBR), which is considered to be run by
SpringSource and also hosts all the libraries that integrate with Spring.
4. Public Maven repository hosted on Amazon S3 for the development of
snapshots and milestone releases. The jar file names are given in the same
form as Maven Central, which makes it a useful place to get development
versions of Spring to use with other libraries Spring Framework deployed in
Maven Central.
|
What are the features
of the new spring build system in use now days?
|
Now the
new Spring build system is used which comes with the following features :
1. "Spring Built" system which is based on Ivy
2. consistent procedure for deployment
3. dependency management which is made consistent
4. consistent generation for OSGi
|
List in brief the new
features Spring 3.0 has to offer
|
Spring 3.0 offers the following new features:
1. Spring Expression Language
2. IoC enhancements or Java based bean metadata
3. field formatting and General-purpose type conversion system
4. Object to XML mapping functionality (OXM) moved from Spring Web Services
project
5. Comprehensive REST support
6. @MVC additions
7. Declarative model validation
8. Early support for Java EE 6
9. Embedded database support
|