Skip to main content

Spring Interview Question - Version 3.5


Spring Overview


Question :  What is Spring?
Answer : Spring is an open source development framework for Enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make Java EE development easier to use and promote good programming practice by enabling a POJO based programming model.
 
Question : What are benefits of Spring Framework?
Answer :  
Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
 
Inversion of control (IOC): Loose coupling is achieved in Spring, with the Inversion of Control technique. The objects give their dependencies instead of creating or looking for dependent objects.
 
Aspect oriented (AOP): Spring supports Aspect oriented programming and separates application business logic from system services.
 
Container: Spring contains and manages the life cycle and configuration of application objects.
 
MVC Framework: Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks.

Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction and scale up to global transactions (JTA).
 
Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO) into consistent, unchecked exceptions. 

Question :Which are the Spring framework modules?
Answer : The basic modules of the Spring framework are :
  • Core module
  • Bean module
  • Context module
  • Expression Language module
  • JDBC module
  • ORM module
  • OXM module
  • Java Messaging Service(JMS) module
  • Transaction module
  • Web module
  • Web-Servlet module
  • Web-Struts module
  • Web-Portlet module
Question : Explain the Core Container (Application context) module.
Answer : This is the basic Spring module, which provides the fundamental functionality of the Spring framework. BeanFactory is the heart of any spring-based application. Spring framework was built on the top of this module, which makes the Spring container.

Question : BeanFactory - BeanFactory implementation example?
Answer : 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. The most commonly used BeanFactory implementation is the XmlBeanFactory class before 3.0. As of 3.0 XmlBeanFactory is depricated, and now DefaultListableBeanFactory is used from 3.0 version belows is the example on which how the DefaultListableBeanFactory is initialized using the XML file.


//Creating the default bean factory, from 3.x of the spring
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
//creating the XML bean definition reader and adding the beanfactory to it, from 3.x of the spring
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
//loading the bean definition from the XML File
beanDefinitionReader.loadBeanDefinitions("com/corespring/beans/basicbean/servlet-context.xml");
//Getting the bean using the id name
BasicBean basicBeanId =    beanFactory.getBean("basicBean", BasicBean.class);


Question : What is ApplicationContext?
Answer : In Spring, the ApplicationContext interface is an extension to BeanFactory. In addition to DI services, the ApplicationContext also provides other services, such as transaction and AOP service, message source for internationalization (i18n), and application event handling, to name a few. In developing Spring-based application, it’s recommended that you interact with Spring via the ApplicationContext interface. Spring supports the bootstrapping of ApplicationContext by manual coding (instantiate it manually and load the appropriate configuration) or in a web container environment via the ContextLoaderListener.

Question : Can we briefly talk about few namespace used along with the application context.
context: The context namespace provides support for configuring Spring’s ApplicationContext.
p: The p namespace provides a simpler DI configuration for Setter Injection.
c: New in Spring 3.1, the c namespace provides a more simple DI configuration for Constructor Injection.
util: The util namespace provides some useful utilities for DI configuration.


Question : Explain the AOP module
Answer : The AOP module is used for developing aspects for our Spring-enabled application. Much of the support has been provided by the AOP Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces metadata programming to Spring.
 
Question : Explain the JDBC abstraction and DAO module With the JDBC abstraction and DAO module?
Answer : we can be sure that we keep up the database code clean and simple, and prevent problems that result from a failure to close database resources. It provides a layer of meaningful exceptions on top of the error messages given by several database servers. It also makes use of Spring’s AOP module to provide transaction management services for objects in a Spring application.
  
Question : What is Spring IoC container?Answer : The Spring IoC is responsible for creating the objects,managing them (with dependency injection (DI)), wiring them together, configuring them, as also managing their complete lifecycle.
 
Question : What are the benefits of IOC?Answer : IOC or dependency injection minimizes the amount of code in an application. It makes easy to test applications, since no singletons or JNDI lookup mechanisms are required in unit tests. Loose coupling is promoted with minimal effort and least intrusive mechanism. IOC containers support eager instantiation and lazy loading of services.
 
Question : What are the common implementations of the ApplicationContext?
Answer
: The FileSystemXmlApplicationContext container loads the definitions of the beans from an XML file. The full path of the XML bean configuration file must be provided to the constructor. 
The ClassPathXmlApplicationContext container also loads the definitions of the beans from an XML file. Here, you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH. The WebXmlApplicationContext container loads the XML file with definitions of all beans from within a web application.

Question : What is the difference between Bean Factory and ApplicationContext?
Answer :
Application contexts provide a means for resolving text messages, a generic way to load file resources (such as images), they can publish events to beans that are registered as listeners. In addition, operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation
being pluggable.

Dependency Injection

Question : What is Dependency Injection in Spring?
Answer : Dependency Injection, an aspect of Inversion of Control (IoC), is a general concept, and it can be expressed in many different ways.This concept says 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 (the IOC container) is then responsible for hooking it all up.

Question : What are the different types of IoC (dependency injection)?
Answer : List of DI are as follows :
  • Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
  • Setter-based dependency injection: Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
Question : Which DI would you suggest Constructor-based or setter-based DI?
Answer : You can use both Constructor-based and Setter-based Dependency Injection. The best solution is using constructor arguments for mandatory dependencies and setters for optional dependencies.
 
Question : Can we declare Constructor as well as Setter Based Injection for the same bean?
Answer : Yes we can do that, e.g 
<bean id="employee" class="com.Initvsinjection.Employee"
              init-method="init">
              <constructor-arg name="id" value="1"></constructor-arg>
              <constructor-arg name="name" value="Bijay"></constructor-arg>
              <constructor-arg name="dob" value="05/05/1980"></constructor-arg>
              <property name="id" value="1" />
              <property name="name" value="vikash" />
              <property name="dob" value="05/05/1980" />
</bean>
The catch is constructor injection will be called first and then  setter injection hence value provided by the setter injection will be the final value.


Question : Explain the role of ApplicationContext in spring. 
Answer : 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. 

Question : What are the id generator classes in hibernate? 
Answer : 
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.

Question : How is a typical spring implementation look like? 
Answer : 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.


Question :  How do you define hibernate mapping file in spring? 
Answer : 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 >


Question :  How do you configure spring in a web application? 
Answer : It is very easy to configure any J2EE-based web application to use Spring. 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 >


Question : Can you have xyz.xml file instead of applicationcontext.xml? 
Answer : 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 >

Question : How do you configure your database driver in spring? 
Answer : 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 >


Question : How can you configure JNDI instead of datasource in spring applicationcontext.xml? 
Answer : 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 >

Question : What are the key benefits of Hibernate? 
Answer : 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

Question : What is hibernate session and session factory? How do you configure sessionfactory in spring configuration file? 
Answer : 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) { }
}
}

Question : What is the difference between hibernate get and load methods? 
Answer : 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.

21. 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 >

Question : JTA vs Non JTA transation Management?
AnswerPA implementations have the choice of managing transactions themselves (RESOURCE_LOCAL), or having them managed by the application server's JTA implementation.
In most cases, RESOURCE_LOCAL is fine. This would use basic JDBC-level transactions. The downside is that the transaction is local to the JPA persistence unit, so if you want a transaction that spans multiple persistence units (or other databases), then RESOURCE_LOCAL may not be good enough.
JTA is also used for managing transactions across systems like JMS and JCA, but that's fairly exotic usage for most of us.
To use JTA, you need support for it in your application server, and also support from the JDBC driver


Comparing RESOURCE_LOCAL and JTA persistence contexts

With <persistence-unit transaction-type="RESOURCE_LOCAL"> YOU are responsible for EntityManager (PersistenceContext/Cache) creating and tracking...
  • You must use the EntityManagerFactory to get an EntityManager
  • The resulting EntityManager instance is a PersistenceContext/Cache
  • An EntityManagerFactory can be injected via the @PersistenceUnit annotation only (not @PersistenceContext)
  • You are not allowed to use @PersistenceContext to refer to a unit of type RESOURCE_LOCAL
  • You must use the EntityTransaction API to begin/commit around every call to your EntityManger
  • Calling entityManagerFactory.createEntityManager() twice results in two separate EntityManager instances and therefor two separate PersistenceContexts/Caches.
  • It is almost never a good idea to have more than one instance of an EntityManager in use (don't create a second one unless you've destroyed the first)

With <persistence-unit transaction-type="JTA"> the CONTAINER will do EntityManager (PersistenceContext/Cache) creating and tracking...
  • You cannot use the EntityManagerFactory to get an EntityManager
  • You can only get an EntityManager supplied by the container
  • An EntityManager can be injected via the @PersistenceContext annotation only (not @PersistenceUnit)
  • You are not allowed to use @PersistenceUnit to refer to a unit of type JTA
  • The EntityManager given by the container is a reference to the PersistenceContext/Cache associated with a JTA Transaction.
  • If no JTA transaction is in progress, the EntityManager cannot be used because there is no PersistenceContext/Cache.
  • Everyone with an EntityManager reference to the same unit in the same transaction will automatically have a reference to the same PersistenceContext/Cache
  • The PersistenceContext/Cache is flushed and cleared at JTA commit time


Question : What is lazy loading and how do you achieve that in hibernate? 
Answer : 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.

Question : What are different types of cache hibernate supports? 
Answer : 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.

Question :What are the different caching strategies? 
Answer : 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.

Question :  How do you configure 2nd level cache in hibernate? 
Answer : 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.

Question :  What is the difference between sorted and ordered collection in hibernate? 
Answer : A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause.

Question :  What are the types of inheritance models and describe how they work like vertical inheritance and horizontal? 
Answer : 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


Question : Give the order in which factory-method, init, setter injection and constructor injection get called?
Answer : Following is the order in which the all the methods will be called 
1) factory-method  
2) constructor injection will be ignored as the constrcutor will be called from factory-method,  based on constructor-arg the appropriate factory-method will chosen and then constructor will be called. 
3) setter injection 
4) init-method



Question : What will happen when we have cyclic dependency, and we are trying to use constructor injection, to resolve the dependancy?
Answer : This will throw an error, as it will not able to find either of the bean, which ever start it's initialization first.

Question : What will happen if the setter method is not present and we are trying to use setter injection.
Answer : In that case it will throw an error, of not finding the setter method.

Question : What will happen if the autowiring type is byName and setter method is missing.
Answer : The dependent bean will not be initialized, and will remain null.

Question : What will happen if the autowiring type is byType and setter method is missing.
Answer : The dependent bean will not be initialized, and will remain null.

Question : What will happen if the autowiring type is constructor and setter method is missing.
Answer : The dependent bean is present in the container, and then it will find what is the best matching constructor, and it will be used.


Question : What will happen if the argument specified in constructor are not able to find the specific constructor, and could be matching with one or two constructor, remotely like one argument is matched with one constructor and another matches with the another constructor.
Answer : We will get the error, while starting of the bean, like ambiguous constructor arguments.


Question : What will happen if the constructors are having the same arguments, only the orders are different, e.g. if the constructor(TypeA a, TypeB b) and  constructor(TypeB a, TypeA a).
Answer : It has been observed that, there is no issue, but only thing is whichever constructor is declared last will be used as the constructor for initializing the bean.

Spring Beans

Question : What are Spring beans?
Answer: The Spring Beans are Java Objects that form the backbone of a Spring application. They are instantiated, assembled, and managed by the Spring IoC container. These beans are created with the configuration metadata that is supplied to the container, for example, in the form of XML <bean/> definitions. 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.


Question : What does a Spring Bean definition contain?
Answer : A Spring Bean definition contains all configuration metadata which is needed for the container to know how to create a bean, its lifecycle details and its dependencies.
 
Question : How do you provide configuration metadata to the Spring Container?
Answer : There are three important methods to provide configuration metadata to the Spring Container:
  • XML based configuration file.
  • Annotation-based configuration
  • Java-based configuration
Question How do you define the scope of a bean?
Answer : When defining a <bean> in Spring, we can also declare a scope for the bean. It can be defined through the scope attribute in the bean definition. For example, when Spring has to produce a new bean instance each time one is needed, the bean’s scope attribute to be prototype. On the other hand, when the same instance of a bean must be returned by Spring every time it is needed, the the bean scope attribute must be set to singleton.
 
Question : Explain the bean scopes supported by Spring
Answer : There are five scoped provided by the Spring Framework supports following five scopes:
  • In singleton scope:  Spring scopes the bean definition to a single instance per Spring IoC container.
  • In prototype scope: a single bean definition has any number of object instances.
  • In request scope: a bean is defined to an HTTP request. This scope is valid only in a web-aware Spring ApplicationContext.
  • In session scope: a bean definition is scoped to an HTTP session. This scope is also valid only in a web-aware Spring ApplicationContext.
  • In global-session scope, a bean definition is scoped to a global HTTP session. This is also a case used in a web-aware Spring ApplicationContext.
Note : The default scope of a Spring Bean is Singleton.
 
Question :  Are Singleton beans thread safe in Spring Framework?
Answer  : No, singleton beans are not thread-safe in Spring framework.
 
Question : Explain Bean lifecycle in Spring framework?
Answer :  Following is life cycle for the spring bean.
  • The spring container finds the bean’s definition from the XML file and instantiates the bean.
  • Spring populates all of the properties as specified in the bean definition (DI).
  • If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.
  • If Bean implements BeanClassLoaderAware interface, spring passes the classLoader to setBeanClassLoader() method.
  • If Bean implements ApplicationContextAware/BeanFactoryAware interface, spring passes the applicationContect/beanfactory to setBeanFactory()/setApplicationContext method.
  • If there are any bean @PostConstruct associated with the bean, Spring calls the method.
  • If the bean implements IntializingBean, its afterPropertySet() method is called. 
  • If the bean has init method declaration, the specified initialization method is called.
  • If @PreDestroy annotation is found then, container need to call the annotated method.
  • If the bean implements DisposableBean, it will call the destroy() method.
  • If the bean has destroy-method then container need to call the specified the destory method.
Question : Explain Bean lifecycle in Spring framework using the code example in terms xml and annotaion declaration?
Follwing is the java bean declared with the all possible lifecycle interface and annotation

@Component(value="Temp" )
public class Temp implements BeanNameAware, ApplicationContextAware, InitializingBean, DisposableBean{     
       @Value(value="1")
       public Integer id;
       @Value(value="vikash")
       public String name;
       @Override
       public String toString() {return "Temp [id=" + id + ", name=" + name + "]";}     
       public Temp(){System.out.println("Step 1 : Instance Created");}     
       public String getName() {return name;}  
       public void setName( String name) { System.out.println("Step 2 : Setters called"); this.name = name;}
       public Integer getId() {return id;}
       public void setId(Integer id) {this.id = id;}  
      
       //Bean Name Aware
       @Override
       public void setBeanName(String name) {
              System.out.println("Step 3 : called bean name aware");       
       }
      
       @Override
       public void setApplicationContext(ApplicationContext applicationContext)
                     throws BeansException {
              System.out.println("Step 4 : setApplicationContext is called");
             
       }
      
       @Override
       public void afterPropertiesSet() throws Exception {
              System.out.println("Step 5 : This is called after bean initialization");
             
       }
      
      
       //Init method
       public void init(){
              System.out.println("Step 6 : Init method is called");
       }
      
       /* (non-Javadoc)
        * @see org.springframework.beans.factory.DisposableBean#destroy()
        */
       @Override
       public void destroy() throws Exception {
              System.out.println("Step 7 : destroy method is called");
             
       }
      
      
      
       public void destroyMethod() throws Exception {
              System.out.println("Step 8 :destroyMethod method is called");
             
       }
       @PostConstruct
       public void postConstruct(){
              System.out.println("postConstruct method is called");
       }
      
       @PreDestroy
       public void preDestroy(){
              System.out.println("preDestroy method is called");
       }
}
Following is the bean declaraion in the XML file

<bean id="temp" class="com.corespring.beans.LifeCycleBeansDemo.Temp" init-method="init" p:id="1" p:name="Vikash" destroy-method="destroyMethod"></bean>


Step 1 : Instance Created
Step 2 : Setters called
Step 3 : called bean name aware
Step 4 : setApplicationContext is called
Step 5 : This is called after bean initialization
Step 6 : Init method is called
Temp [id=1, name=Vikash]
Step 7 : destroy method is called
Step 8 :destroyMethod method is called

Only thing to observe is it has not called any annotated method, as it is not initialized using the annotation.

Now lets see how it behaves when we are using annotation, for that we have to change our xml file to support component scan

<context:component-scan base-package="com.corespring.beans.LifeCycleBeansDemo">
</context:component-scan>


public class LifeCycleBeanExecuter {
public static void main(String[] args) {
GenericXmlApplicationContext applicationContext = new GenericXmlApplicationContext();
applicationContext.load("com/corespring/beans/LifeCycleBeansDemo/servlet-context.xml");
applicationContext.refresh();
System.out.println(applicationContext.getBean(Temp.class));
//Important step to simulate the shut down of the container, upon which destroy lifecycle will //be called
applicationContext.close();
       }
}


Step 1 : Instance Created
Step 2 : Setters called
Step 3 : called bean name aware
Step 4 : setApplicationContext is called
@postConstruct method is called
Step 5 : This is called after bean initialization
Temp [id=1, name=vijay]
@preDestroy method is called
Step 7 : destroy method is called

Important thing to observe is we are no longer calling init-method and destroy-method as it is annontaion based and it doesn't know anything about those attributes declared. But important thing to notice in both the scenario the lifecycle interface methods from the following interfaces
1. BeanNameAware 
2. ApplicationContextAware 
3. InitializingBean 
4. DisposableBean

are not missed and are called in the same order.

Question : Practically what is the diffrenece between annotation-config and component scan, more or less it's looks same?
Answer : Both are not same thing, it Activates various annotations to be detected in bean classes: Spring's @Required and @Autowired, as well as JSR  250's @PostConstruct, @PreDestroy and @Resource (if available), JAX-WS's @WebServiceRef (if available), EJB3's  @EJB (if available), and JPA's @PersistenceContext and @PersistenceUnit (if available). Alternatively, you may  choose to activate the individual BeanPostProcessors for those annotations. 

One thing to be cautious is this tag does not activate  processing of Spring's @Transactional or EJB3's @TransactionAttribute annotation. Consider the use of the  <tx:annotation-driven> tag for that purpose.if we enable the annotations using the context:annotation-config.
Look at the below example, the code remain as it as it was in the above example.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
       ">
       <context:annotation-config  />
       <bean id="temp" class="com.corespring.beans.LifeCycleBeansDemo.Temp"
              init-method="init" p:id="1" p:name="Vikash" 
              destroy-method="destroyMethod" scope="singleton">
      </bean>
</beans>


The output is now little bit varying, the init attribute from the spring xml file and @PreConstruct annotated method is called, after we activated the context: annotation-config.

Step 1 : Instance Created
Step 2 : Setters called
Step 3 : called bean name aware
Step 4 : setApplicationContext is called
postConstruct method is called
Step 5 : This is called after bean initialization
Step 6 : Init method is called
Temp [id=1, name=Vikash]
Aug 03, 2015 3:40:33 PM org.springframework.context.support.GenericXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.GenericXmlApplicationContext@5010be6: startup date [Mon Aug 03 15:40:32 IST 2015]; root of context hierarchy
preDestroy method is called
Step 7 : destroy method is called
Step 8 :destroyMethod method is called
So as per defination, here context:annotation-config is activating the annotation for the registered beans, which are registered using the xml declarations, or using the component scan, but the major diff between annotaion-config and component scan is,  component scan will activate the annotation and also find the beans which are either annotated with the @Component or any other annotation which are child or precisely stereo type of it like @Controller or @Service or @Repository etc. but it ignores the bean which are not registered via component scan , that means all the annotation which are applied on the non component annotated class will have no meaning unless we specify the context:annotation-config.

Question : If the bean scope is changed from the singleton to prototype, in that case will there be any change in the lifecycle?
Answer : Yes there is slight change in the behavior, upon the shut down of the container no @Predestroy or destroy method or disposableBean implementing method destroy will not be called, other wise it will remain as it is.

Question : Which are the important beans lifecycle methods? Can you override them?
Answer : 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. The bean tag has two important attributes (init-method and destroy-method) with which you can define your own custom initialization and destroy methods. There are also the correspondive annotations(@PostConstruct and @PreDestroy).


Question : How can we give alias name to the bean, and how can we use them?


<bean id="temp" name="tempa tempB" class="com.corespring.beans.basicbean.BasicBean" >
       <property name="id" value="1"></property>
       <property name="tempName" value="vikash"></property>
</bean>

//Creating the default bean factory, from 3.x of the spring
              DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
              //creating the XML bean definition reader and adding the beanfactory to it, from 3.x of the spring
              XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
              //loading the bean definition from the XML File
              beanDefinitionReader.loadBeanDefinitions("com/corespring/beans/basicbean/servlet-context.xml");
              //Getting the bean using the id name
              BasicBean basicBeanId =    beanFactory.getBean("temp", BasicBean.class);
              //Getting the bean using the alias name
              BasicBean basicBeanbAlias =       beanFactory.getBean("tempa", BasicBean.class);

Question : Is it possible to have id and name same for the bean definition?
Answer : It is fine to have name and id to be same, id represent the unique identifier of the bean and name represent the alias of the bean, id can be only one but alias can be many, like above example where we have id=temp and name = "tempa tempB", so for the id=temp we have two alias name i.e. tempa and tempB. we also need to make sure that alias name canot be use for the other bean neither as id nor as name, that also should be unique.

Question : Can a bean id contain name having the space e.g <bean id="vikash chandra mishra"?
Answer : Surprisingly It is allowed, but only thing is I am sure it is not a good practice to have such id.

Question : How can we use the <alias> tag to give the bean alias name.
Answer : Following example shows how and what are the valid ways to create the alias using the tag.
<!-- creating bean and adding the alias name using the name attribute -->
<bean id="temp" name="temp1,temp2" class="com.corespring.beans.ApplicationContext.Temp">
</bean>
<!-- creating the alias using the alias name is very much valid -->
<alias name="temp1" alias="temp3"/>
<!-- creating the alias using the id is very much valid -->
<alias name="temp" alias="temp3"/>

Question :  What are inner beans in Spring? 
Answer : When a bean is only used as a property of another bean it can be declared as an inner bean. Spring’s XML-based configuration metadata provides the use of <bean/> element inside the <property/> or <constructor-arg/> elements of a bean definition, in order to define the so-called inner bean. Inner beans are always anonymous and they are always scoped as prototypes.

Question :  How can you inject a Java Collection in Spring?
Answer
: Spring offers the following types of collection configuration elements:
  • The <list> type is used for injecting a list of values, in the case that duplicates are allowed.
  • The <set> type is used for wiring a set of values but without any duplicates.
  • The <map> type is used to inject a collection of name-value pairs where name and value can be of any type.
  • The <props> type can be used to inject a collection of name-value pairs where the name and value are both Strings.
Question : What is bean wiring? 
Answer : Wiring, or else bean wiring is the case when beans are combined together within the Spring container. When wiring beans, the Spring container needs to know what beans are needed and how the container should use dependency injection to tie them together.

Question : What is bean auto wiring?
Answer
: The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for a bean by inspecting the contents of the BeanFactory without using <constructor-arg> and <property> elements.


Question : Explain different modes of auto wiring?
Answer : The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection:
  • no: This is default setting. Explicit bean reference should be used for wiring.
  • byName: When autowiring byName, the Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.
  • byType: When autowiring by datatype, the Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown.
  • constructor: This mode is similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.
  • autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
Question : What is abstract="true"?
Answer : This is like creating template bean, in which we can have default value of all the variables and for the real life can inherit it's property. The bean can be a concrete java class and it need not to be a concrete class, e.g. 


<!-- creating abstract bean populating all the attribute can be used by child bean, additionally the bean is not referring to any class -->
<bean id="myAbstractClass" abstract="true" p:id="54" p:name="killer">
</bean>
<!-- creating bean and using the attributes of the abstract bean, we need to make sure the names used has be same in the actual bean -->
<bean id="temp" name="temp1,temp2" class="com.corespring.beans.ApplicationContext.Temp" parent="myAbstractClass">
</bean>

Question : Give small example of using spel, i.e. spring expression language.
Answer : example and usage of spel in the xml file, same can be used in the @value annotaion.
<!-- Contains default data for the id and name -->
<bean id="spelData" class="com.corespring.ApplicationContext.Temp" p:id="54" p:name="killer">
</bean>
<!-- referring the data from the above bean using spel -->
<bean id="temp" name="temp1,temp2" class="com.corespring.ApplicationContext.Temp">
       <property name="id" value="#{spelData.id}"></property>
       <property name="name" value="#{spelData.name}"></property>
</bean>

Question : What is primary="true"?
Answer : Specifies that this bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. E.g. 
<bean id="employee" class="com.Autowiring.Employee" autowire="byType"/>
      
       <bean name="address1" class="com.Autowiring.Address">
              <property name="city" value="Bangalore" />
              <property name="zip" value="560103" />
              <property name="building" value="Shri Paradise" />
       </bean>
      
       <bean name="address2" class="com.Autowiring.Address" primary="true">
              <property name="city" value="Bokaro" />
              <property name="zip" value="827009" />
              <property name="building" value="1st building" />
</bean>


Since it autowire="byType" then while wiring the beans it will get confused as which address it should given

Question : What will happen if the autowiring = byType/byName/constructor, and also setter injection using <property> tag for the same property e.g.
     <bean id="employee" class="com.Autowiring.byType.Employee" autowire="byType">
        <property name="address" ref="address1"></property>
    </bean>
      
       <bean name="address1" class="com.Autowiring.Address">
              <property name="city" value="Bangalore" />
              <property name="zip" value="560103" />
              <property name="building" value="Shri Paradise" />
       </bean>
      
       <bean name="address2" class="com.Autowiring.Address" primary="true">
              <property name="city" value="Bokaro" />
              <property name="zip" value="827009" />
              <property name="building" value="1st building" />
</bean>


Answer : In that case the setter injection will override values set by Auto Wiring.

Question : When Autowiring byType then do we need setter method?
Answer : Ideally it should not be, but it is required.

Question : Is it necessary to have default constructor for all the bean if the bean has argument constructor?
Answer : Yes, we need to have to default constructor, else we need to pass the constructor-arg with the each and every bean declaration in the XML file like as follows.
<bean id="basicChildBean" class="com.corespring.beans.basicbean.BasicChildBean">
       <constructor-arg name="name" value="basicChildBean"></constructor-arg>
</bean>
If we miss any for any bean of the given type then we will get bean initialization exception, on the startup of the container.

Question : What are there limitations with autowiring?
Answer : Limitations of autowiring are:
  • Overriding: You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.
  • Primitive data types: You cannot autowire simple properties such as primitives, Strings, and Classes.
  • Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.
Question : Can you inject null and empty string values in Spring beans?
Answer
: Yes, we can.


Question : What will happen when we have multiple constructor and autowiring type is constructor?
Answer : Look at my answer by clicking on the following link.
Answer in stack overflow.com


More precisely below example can help you to understand, So I have one class Employee and it has has a relationship with the qualification and address, and bean are available inside the xml declaration.
<bean id="employee" class="com.Autowiring.constructor.Employee" autowire="constructor">
              <constructor-arg name="id" value="1"/>
              <constructor-arg name="name" value="vikash"/>
              <constructor-arg name="dob" value="05/05/1980"/>
       </bean>
      
       <bean id="qualification" class="com.Autowiring.constructor.Qualification">
              <property name="highestQualification" value="BTech"/>
              <property name="certifcations" value="SCJP"/>
       </bean>
      
       <bean name="address" class="com.Autowiring.constructor.Address">
              <property name="city" value="Bangalore" />
              <property name="zip" value="560054" />
              <property name="building" value="Building One" />
       </bean>

We have 4 constructors 1st  takes two argument i.e. Address and Qualification and 2nd  takes Qualification  and 3rd constructor takes the Address and then 4th one takes all the fields starting from id,name,dob,address and qualification.
//Constructor 1
public Employee(Address address, Qualification qualification) {
              super();
              System.out.println(1);
              this.address = address;
              this.qualification = qualification;
       }
//Constructor 2
public Employee(Qualification qualification) {
              super();
              System.out.println(2);
              this.qualification = qualification;
       }

//Constructor 3
public Employee(Address address) {
              super();
              System.out.println(3);
              this.address = address;
       }
//Constructor 1
public Employee(int id, String name, Date dob, Address address,
                     Qualification qualification) {
             
              super();
              System.out.println(4);
              this.id = id;
              this.name = name;
              this.dob = dob;
              this.address = address;
              this.qualification = qualification;
       }
      

Case-1: Let’s assume Constructor 1 and 4 is not declared and we don’t have constructor-arg in the employee bean declarations.
Behavior: constructor 3 will be called as this the last constructor declared, if we change the order of definition of constructors i.e. swap  the position of constructor 2 with 3.
Case-2: Let’s assume Constructor 4 is not declared, and we don’t have constructor-arg in the employee bean declarations.
Behavior: In that case constructor 1 will be called, as it can get the type Qualification and Address available in the bean declarations, so this satisfy the condition for the matching arguments for constructor 1.
Case-3:  Let’s assume we don’t have constructor-arg in the employee bean declarations.
Behavior: In that case also constructor 1 will be called, as it can get the type Qualification and Address available in the bean declarations, so this satisfy the condition for the matching arguments for constructor 1, but it will not able to call the 4th constructor as the id,name, and dob are not available in the bean declaration file , so 1st constructor is the best matching  constructor as we have Qualification and Address available in the bean declaration.
Case-4: Let’s assume we have constructor-arg in the employee bean declarations, and all constructors are available.
Behavior: It will able to call the 4th constructor as the id, name, dob, qualification and address  are available in the bean declaration  file , so 1st 3 argument will come from constructor arg and last two will come from the declaration of the bean itself hence all argument from the 4th constructor matching  hence 4th constructor will be called.
Conclusion :   So the cases and behavior suggests that, in case of multiple constructors, spring container tries to verify all the dependent properties and verify based on all the available property which among the constructors can be used to create the object, where maximum possible properties can be initialized.
 
Question : What is factory-method?
Answer : The name of a factory method to use to create this object. Use constructor-arg elements to specify arguments to  the factory method, if it takes arguments. Autowiring does not apply to factory methods. If the "class" attribute is  present, the factory method will be a static method on the class specified by the "class" attribute on this bean  definition. Often this will be the same class as that of the constructed object - for example, when the factory  method is used as an alternative to a constructor. However, it may be on a different class. In that case, the  created object will *not* be of the class specified in the "class" attribute. This is analogous to FactoryBean  behavior. If the "factory-bean" attribute is present, the "class" attribute is not used, and the factory method will  be an instance method on the object returned from a getBean call with the specified bean name. The factory  bean may be defined as a singleton or a prototype. The factory method can have any number of arguments.  Autowiring is not supported. Use indexed constructor-arg elements in conjunction with the factory-method  attribute. Setter Injection can be used in conjunction with a factory method. Method Injection cannot, as the  factory method returns an instance, which will be used when the container creates the bean.

Question : Show the demo code to elaborate more, for the factory-method.
Answer : Add the declaration in the xml file,

<bean id="basicBean" class ="com.corespring.beans.factorymethodclass.FactoryMadeBean"
              autowire="byType" factory-method="getFactoryMadeBean">
</bean>

Now add the static method in the same class, 
public static FactoryMadeBean getFactoryMadeBean()
{
       System.out.println("Called the factory Method");
       FactoryMadeBean bean = new FactoryMadeBean();
       return bean;
}

Question : Is that possible that if we can pass the arguments also in the factory method?
Answer: It's very much possible, 
Step 1 : Declare the factory method to accept the arguments, 

public static FactoryMadeBean getFactoryMadeBean(int id, String name,String tempName)
{
       System.out.println("Called the factory Method");
       FactoryMadeBean bean = new FactoryMadeBean();
       bean.setId(id);
       bean.setTempName(tempName);
       bean.setName(name);       
       return bean;
}

Now add constructor-arg with the same order in which method has declared the arguments,

<bean id="basicBean" class ="com.corespring.beans.factorymethodclass.FactoryMadeBean"
              autowire="byType" factory-method="getFactoryMadeBean">       
       <constructor-arg index="0" value="1" type="int"></constructor-arg>
       <constructor-arg index="1" value="Vikash"></constructor-arg>
       <constructor-arg index="2" value="Vikash Chandra"></constructor-arg>
</bean>

Spring Annotations


Question : What is Spring Java-Based Configuration? Give some annotation example.
Answer : Java based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations. An example is the @Configuration annotation, that indicates that the class can be used by the Spring IoC container as a source of bean definitions. Another example is the @Bean annotated method that will return an object that should be registered as a bean in the Spring application context.

Question : What is Annotation-based container configuration?
Answer : An alternative to XML setups is provided by annotation-based configuration which relies on the bytecode metadata for wiring up components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration.
 
Question : How do you turn on annotation wiring?
Answer : Annotation wiring is not turned on in the Spring container by default. In order to use annotation based wiring we must enable it in our Spring configuration file by configuring <context:annotation-config/> element.


Question : How to register the annotated beans?
Answer : in Xml file we need to provide the tags to support.
<context:component-scan base-package="com.corespring.beans.ApplicationContext" ></context:component-scan>
We can have multiple lines for the same if we want to scan multiple packages.

Question : @Required annotation
Answer : This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring. The container throws BeanInitializationException if the affected bean property has not been populated.

Question : @Autowired annotation
Answer : The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. It can be used to autowire bean on the setter method just like @Required annotation, on the constructor, on a property or on methods with arbitrary names and/or multiple arguments.


Question : @Scope annotation?
Answer : This is to provide the scope of the bean, by default all beans are singleton, but if we want we can change the behavior by providing the @Scope annotation.
@Scope(value=DefaultListableBeanFactory.SCOPE_SINGLETON) 
@Scope(value=DefaultListableBeanFactory.SCOPE_PROTOTYPE)

Question : What is @Qualifier annotation
Answer
: When there are more than one beans of the same type and to resolve the DI , the @Qualifier annotation is used along with @Autowired annotation to resolve the confusion by specifying which exact bean will be wired. e.g. if there are multiple implementation of the same interface and wiring is done based on the interface name, then @Qualifier will help us to identify the bean to be injected at the run time.


Question : Can you give the example code to demonstrate the @Qualifier?
Answer : Following is the example to demo the @Qualifier
Created the Interface
public interface TempChildInterface {
       public String getChildName();
}

Created implementation of the interface
@Component("ElderChildImpl")
public class ElderChildImpl implements TempChildInterface {
       @Value("Ramesh")
       private String name;
       @Override
       public String getChildName() {
              return name;
       }     
       @Override
       public String toString() {
              return "ElderChildImpl [name=" + name + "]";
       }
}


@Component("MiddleChildImpl")
public class MiddleChildImpl implements TempChildInterface {
       @Value("Hitesh")
       private String name;
       @Override
       public String getChildName() {
              return name;
       }
       @Override
       public String toString() {
              return "MiddleChildImpl [name=" + name + "]";
       }
}

Now creating the main class in which the interface will be auto wired,
@Component(value="Temp")
public class Temp { 
       @Value(value="1")
       private Integer id;
       @Value(value="vikash")
       private String name;
       @Autowired(required=true)//We observed true/false is not able to stop the bean container initilization.
       private TempChildInterface tempChildInterface
       @Override
       public String toString() {
              return "Temp [id=" + id + ", name=" + name + ", tempChildInterface="
                           + tempChildInterface + "]";
       }     
}
But as we have two implementation so we will get the following error
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.corespring.beans.ApplicationContext.TempChildInterface] is defined: expected single matching bean but found 2: ElderChildImpl,MiddleChildImpl
Now we will add the qualifier annotation and see if it works
@Component(value="Temp")
public class Temp { 
       @Value(value="1")
       private Integer id;
       @Value(value="vikash")
       private String name;
       @Autowired(required=false)
       @Qualifier("MiddleChildImpl")
       private TempChildInterface tempChildInterface
       @Override
       public String toString() {
              return "Temp [id=" + id + ", name=" + name + ", tempChildInterface="
                           + tempChildInterface + "]";
       }     
}
We will try to run and we get the following output
public class ApplicationContextExecuter {
       public static void main(String[] args) {
              GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
              ctx.load("com/corespring/beans/ApplicationContext/servlet-context.xml");
              ctx.refresh();
              System.out.println(ctx.getBean(Temp.class));          
       }
}

Temp [id=1, name=vikash, tempChildInterface=MiddleChildImpl [name=Hitesh]]

If we change the @Qualifier to @Qualifier("ElderChildImpl") then output will be as follows

Temp [id=1, name=vikash, tempChildInterface=ElderChildImpl [name=Ramesh]]


Question : @Resource annotaton from JSR-250 standard?
Answer : The two lines of code from above example i.e
       @Autowired(required=false)

       @Qualifier("MiddleChildImpl")
can be replaced with the one line by using @Resource annotation.
@Resource(name="ElderChildImpl"), only thing which we may miss is the required=false/true is not there as part of @Resource.

Question : @Value annotation?
Answer : @Value annotation has similar usage what we have for the property tag in the XML file, can be used above the field declaration, so that upon initialization, the value will be injected to the field, can be used above the setter method to do the similar task, and for the constructor it should be along with the argument like as follows.
public MiddleChildImpl(@Value(value="pijesh") String name){
              this.name = name;
}

Question : How can we use p tag, show the example code.
Answer : Following is the Component/Bean class

@Component(value="Temp" )
public class Temp { 
       @Value(value="1")
       public Integer id;
       @Value(value="vikash")
       public String name;
       @Autowired(required=false)
       @Resource(name="ElderChildImpl")
       private TempChildInterface tempChildInterface
       @Override
       public String toString() {
              return "Temp [id=" + id + ", name=" + name + ", tempChildInterface="
                           + tempChildInterface + "]";
       }     
}
 Now to provide the setter injection we can use p:tag directly rather creating multiple property tags in side the bean declaration.

<bean id="temp" class="com.corespring.beans.ApplicationContext.Temp" p:id="2" p:name="Vijay"></bean>

We also need to make sure we must have public setter method for each and every property which we are trying to access using the p tag, similar to the prerequisite for the setter injection, even if we make the bean property as the public it will not work.

Question : What will happen if we have two constructor, one of the int type and another of String type, upon the following constructor-arg what is the out come and why?

<constructor-arg>
<value>90</value>
</constructor-arg>

Answer : Constructor with the argument type as String will be given precedence, as each value is termed as String in the XMLfile. to avoid that we can declare the constructor-arg as

<constructor-arg type="int">
<value>90</value>
</constructor-arg>

So it clearly specify that the passed value is integer, hence the matching constructor will get called.

Spring Data Access

Question : How can JDBC be used more efficiently in the Spring framework?
Answer : When using the Spring JDBC framework the burden of resource management and error handling is reduced. So developers only need to write the statements and queries to get the data to and from the database. JDBC can be used more efficiently with the
help of a template class provided by Spring framework, which is the JdbcTemplate (example here).
 
Question : What is JdbcTemplate?
Answer : JdbcTemplate class 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.
 
Question :  Spring DAO support?
Answer : 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 us to switch between the persistence technologies fairly easily and to code without worrying about catching exceptions that are specific to each technology.
 
Question : What are the ways to access Hibernate by using Spring?
Answer : There are two ways to access Hibernate with Spring:
  • Inversion of Control with a Hibernate Template and Callback.
  • Extending HibernateDAOSupport and Applying an AOP Interceptor node.
Question : ORM’s Spring suppor
Answer :  Spring supports the following ORM’s: 
  • Hibernate 
  • iBatis 
  • JPA (Java Persistence API)
  • TopLink
  • JDO (Java Data Objects)
  • OJB
Question : How can we integrate Spring and Hibernate using HibernateDaoSupport?
Answer : Use Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps:
  • Configure the Hibernate SessionFactory
  • Extend a DAO Implementation from HibernateDaoSupport
  • Wire in Transaction Support with AOP
Question : Types of the transaction management Spring support
Spring supports two types of transaction management:
  • Programmatic transaction management: This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
  • Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.
Question : What are the benefits of the Spring Framework’s transaction management?
  • It provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
  • It provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
  • It supports declarative transaction management.
  • It integrates very well with Spring’s various data access abstractions.
Question : Which Transaction management type is more preferable?
Answer: 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. Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code.

Spring Aspect Oriented Programming (AOP)

Question :  Explain AOP
Answer : 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.


Question : Explain each points in the AOP?

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

Join point: 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.

Advice: action taken by an aspect at a particular join point. Different types of advice include "around," "before" and "after" advice. (Advice types are discussed below.) Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors around the join point.

Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default.

Introduction: declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any advised object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching. (An introduction is known as an inter-type declaration in the AspectJ community.)

Target object: object being advised by one or more aspects. Also referred to as the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.
AOP proxy: an object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy.

Weaving: linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime. 

Question : What is Aspect?
Answer: The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. It is a module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement. In Spring AOP, aspects are implemented using regular classes annotated with the @Aspect annotation (@AspectJ style).
 
Question : What is the difference between concern and cross-cutting concern in Spring AOP
Answer : The Concern is behavior we want to have in a module of an application. A Concern may be defined as a functionality we want to implement. The cross-cutting concern is a concern which is applicable throughout the application and it affects the entire application. For example, logging, security and data transfer are the concerns which are needed in almost every module of an application, hence they are cross-cutting concerns.
 
Question What is Join point?
Answer: The join point represents a point in an application where we can plug-in an AOP aspect. It is the actual place in the application where an action will be taken using Spring AOP framework.

Question :  What is Advice?
Answer : The advice is the actual action that will be taken either before or after the method execution. This is actual piece of code that is invoked during the program execution by the Spring AOP framework.
Spring aspects can work with five kinds of advice:
  • before: Run advice before the a method execution.
  • after: Run advice after the a method execution regardless of its outcome.
  • after-returning: Run advice after the a method execution only if method completes successfully.
  • after-throwing: Run advice after the a method execution only if method exits by throwing an exception.
  • around: Run advice before and after the advised method is invoked.
What is  Pointcut?
Answer : The pointcut is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns.
 

Question : What is Introduction?
Answer : An Introduction allows us to add new methods or attributes to existing classes.
 

Question : What is Target object?
Answer : The target object is an object being advised by one or more aspects. It will always be a proxy object. It is also referred to as the advised object.
 
Question :  What is a Proxy?
Answer :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. 


Question : Show the code example of the proxy factory.
Answer : Following code will give the demo of the can we use the proxy factory.
Step 1 : Create the bean 

public class Temp  {
       public Integer id;
      
       public String name;
      
       public String getName() {return name;}  
       public void setName( String name) { this.name = name;}
       public Integer getId() {return id;}
       public void setId(Integer id) {this.id = id;}
       //Will be used to demo the AOP around advice.
       public void writeMessage(){
              System.out.print("World");
       }     
}     

Step 2 : Add the declaration in XML file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
       ">
       <bean id="temp" class="com.corespring.beans.AOP.Temp"  p:id="1" p:name="Vikash"></bean>
             
</beans>     

Just for experiment we have created two interceptor of same type i.e. MethodInterceptor, which will be called around the execution of the method.


import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
//Interceptor -  1
public class TempMethodInterceptor1 implements MethodInterceptor {

       @Override
       public Object invoke(MethodInvocation invocation) throws Throwable {
              System.out.print("Hello ");
              Object retVal = invocation.proceed();
              System.out.print("!");
              return retVal;
       }
}
//Interceptor -  2
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class TempMethodInterceptor2 implements MethodInterceptor {

       @Override
       public Object invoke(MethodInvocation invocation) throws Throwable {
              System.out.print("Ola ");
              Object retVal = invocation.proceed();
              System.out.print("!");
              return retVal;
       }

}     

Now Let's create a class to execute the AOP

public class AOPExecuter {
       public static void main(String[] args) {
              GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
              ctx.load("com/corespring/beans/AOP/servlet-context.xml");
              ctx.refresh();
              //Creation of proxy factory important step for activating the AOP
              ProxyFactory pf = new ProxyFactory();
              //Adding the pre created advice, here it is around advice - advice 1
              pf.addAdvice(new TempMethodInterceptor1());
              //Adding the pre created advice, here it is around advice - advice 2
              pf.addAdvice(new TempMethodInterceptor2());
              //Getting the bean from the application context
              pf.setTarget(ctx.getBean("temp",Temp.class));
              //Now the bean is wrapped around the advice, now returning the wrapped advice,
              //one important thing is there is no change in the existing bean,
              //you will observe that if we invoke the method from the original bean
              //then there will be no execution of the advice.
              //First get the bean from Proxy Factory
              Temp proxy = (Temp) pf.getProxy();
              // write the messages target.writeMessage();
              System.out.println("");
              System.out.println("----------------------");
              //Call the method from the bean taken from the proxy factory
              proxy.writeMessage();
              System.out.println("\n----------------------");
              //Call the bean method from application context
              ctx.getBean("temp",Temp.class).writeMessage();
              System.out.println("\n----------------------");
       }
}

Output


----------------------
Hello Ola World!!
----------------------
World
----------------------

As we can see the Hello came from the first interceptor and ola came from the second.


Question : What are the different types of AutoProxying? 
  • BeanNameAutoProxyCreator
  • DefaultAdvisorAutoProxyCreator
  • Metadata autoproxying
Question : Give the example of the BeanNameAutoProxyCreator?
Answer : First of all we need to register the BeanNameAutoProxyCreator class as the bean, basically it has two major property using which it attains the AOP,

beanNames :Set the names of the beans that should automatically get wrapped with proxies. A name can specify a prefix to match by ending with "*", e.g. "myBean,tx*" will match the bean named "myBean" and all beans whose name start with "tx". <p><b>NOTE:</b> In case of a FactoryBean, only the objects created by the FactoryBean will get proxied. This default behavior applies as of Spring 2.0. If you intend to proxy a FactoryBean instance itself (a rare use case, but Spring 1.2's default behavior), specify the bean name of the FactoryBean including the factory-bean prefix "&": e.g. "&myFactoryBean".

interceptorNames : Set the common interceptors. These must be bean names in the current factory. They can be of any advice or advisor type Spring supports. <p>If this property isn't set, there will be zero common interceptors. This is perfectly valid, if "specific" interceptors such as matching Advisors are all we want.

<!-- Bean name auto proxy creator -->
       <beans:bean name="proxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
       <!--
              AOP proxy will be applied All the matching
              bean, here we can use * also like *Controller
              which means any bean with name ending with
              Controller or Employee* which means
              EmployeeController or
              EmployeeDao or
              EmployeeService etc
       -->
    <beans:property name="beanNames">
        <beans:list>
              <!--
                     Here we have used the exact name,
                     instead of wild card so any bean/component
                     having name JQueryController will have
                     aspects
              -->
            <beans:value>JQueryController</beans:value>           
        </beans:list>
    </beans:property>
    <!--
       List of interceptor needed to be applied on the PointCut
    -->
    <beans:property name="interceptorNames">
        <beans:list>
        <!-- Below bean has implemented the  MethodBeforeAdvice-->
         <beans:value>BeforeAdviceInterceptor</beans:value>  
        <!-- Below bean has implemented the  MethodInterceptor-->
         <beans:value>AroundInterceptor</beans:value>
        <!-- Below bean has implemented the  AfterReturningAdvice--> 
         <beans:value>AfterReturningInterceptor</beans:value>        
        </beans:list>
    </beans:property>
</beans:bean>

Now create the interceptor and add the @Component with the desired name.
@Component("BeforeAdviceInterceptor")
public class BeforeAdviceInterceptor implements MethodBeforeAdvice{
       @Override
       public void before(Method method, Object[] args, Object target)
                     throws Throwable {
              System.out.println("Before the advice");       
       }     
}

@Component("AroundInterceptor")
public class AroundInterceptor implements MethodInterceptor{ 
       @Override
       public Object invoke(MethodInvocation invocation) throws Throwable {
              System.out.println("Before invocation of the Method : "+invocation.getMethod().getName());
              Object obj = invocation.proceed();
              System.out.println("After invocation of the Method : "+invocation.getMethod().getName());
              return obj;
       }
}

@Component("AfterReturningInterceptor")
public class AfterReturningInterceptor implements AfterReturningAdvice{
       @Override
       public void afterReturning(Object returnValue, Method method,
                     Object[] args, Object target) throws Throwable {
              System.out.println("After returning");         
       }     
}

Question : How can we use the aop namespace for configuring the AOP?
Answer : Declare the AOP configuration like as follows,
<!--
       A section of AOP-specific configuration (including aspects, pointcuts, etc).
 -->
<aop:config>
<!-- creating the point cuts, the expression will figure all the matching join points -->
<!-- Point cut configuration 1 -->
<aop:pointcut expression="execution(* com.my.springmvc.HomeController.*(..))" id="exe"/>
<!-- Point cut configuration 2-->
<aop:pointcut expression="execution(* com.mvc.jquery.controller.JQueryController.*(..))" id="jqexe"/>

<!-- Aspects configuration 1 -->
<aop:aspect ref="myAspect">
<aop:before method="myAspectMethodBefore" pointcut-ref="exe" />
<aop:around method="myAspectMethodAround" pointcut-ref="exe"/>
<aop:after method="myAspectMethodAfter" pointcut-ref="exe" />
<aop:after-returning method="myAspectMethodAfterReturning" pointcut-ref="exe"/> 
</aop:aspect>

<!-- Aspects configuration 2 -->
<aop:aspect ref="myAspect">
<aop:before method="myAspectMethodBefore" pointcut-ref="jqexe" />
<aop:after method="myAspectMethodAfter" pointcut-ref="jqexe" />
<aop:around method="myAspectMethodAround" pointcut-ref="jqexe"/>
</aop:aspect>

</aop:config>

Now create the component to hold all the Aspect methods, ideally all the method should have the signature as the joinpoint, it will help us add some intelligence into the aspect method, either it should not have any argument or argument type must be JoinPoint, if we try to add any argument other than joinpoint means there is no meaning and it will throw an error while starting of container


public void myAspectMethodBefore(JoinPoint joinPoint){
              System.out.println("myAspectMethodBefore");
              System.out.println("Executing: " +
                           joinPoint.getSignature().getDeclaringTypeName() + " "
                           + joinPoint.getSignature().getName()+ " "+
                           joinPoint.getKind());
}

public void myAspectMethodAfter(JoinPoint joinPoint){
              System.out.println("myAspectMethodAfter");
              System.out.println("Executing: " +
                           joinPoint.getSignature().getDeclaringTypeName() + " "
                           + joinPoint.getSignature().getName()+ " "+
                           joinPoint.getKind());
}

public void myAspectMethodAfterReturning(JoinPoint joinPoint){
              System.out.println("myAspectMethodAfterReturning");
              System.out.println("Executing: " +
                           joinPoint.getSignature().getDeclaringTypeName() + " "
                           + joinPoint.getSignature().getName()+ " "+
                           joinPoint.getKind());
}

public void myAspectMethodAround(ProceedingJoinPoint proceedingJoinPoint){
              System.out.println("myAspectMethodAround started");
              System.out.println("Executing: " +
                           proceedingJoinPoint.getSignature().getDeclaringTypeName() + " "
                           + proceedingJoinPoint.getSignature().getName()+ " "+
                           proceedingJoinPoint.getKind());
             
              try {
                     proceedingJoinPoint.proceed();
              } catch (Throwable e) {
              }     
              System.out.println("myAspectMethodAround ended");
}





Question : What is Spring Interceptor?
Answer In Web application when request comes to the controller , the HandlerMapping handler matches the incoming request. DispatcherServlet will hand it over to the handler mapping, to let it inspect the request and come up with an appropriate HandlerExecutionChain. Then the DispatcherServlet will execute the handler and interceptors in the chain. When it comes to interceptors you can perform the your logic like logging, method tracking etc.

Question : Give example of HandlerInterceptor?
Answer : We need to follow the following basic steps to have Interceptor activated for our spring mvc application.
Step 1 : Create an Interceptor, give the name to the Component, it was not working at first time when we tried to use it without giving the component name, alternatively we can also extend the HandlerInterceptorAdapter If we extend this class then we need not have to implement all the method like preHandle,postHandle and afterCompletion method, we can override whichever method we want to add our own functionality based on the requirement.

@Component("FirstInterceptor")
public class FirstInterceptor implements HandlerInterceptor{
       @Override
       public boolean preHandle(HttpServletRequest request,
                     HttpServletResponse response, Object handlerthrows Exception {
              // TODO Auto-generated method stub
              System.out.println("prehandle");
              return true;
       }
       @Override
       public void postHandle(HttpServletRequest request,
                     HttpServletResponse response, Object handler,
                     ModelAndView modelAndViewthrows Exception {
              System.out.println("posthandle");       
       }

       @Override
       public void afterCompletion(HttpServletRequest request,
                     HttpServletResponse response, Object handler, Exception ex)
                     throws Exception {
              System.out.println("after completion");
             
       }     
}     

Step 2 : Add the declaration into the XML file.

<!--
       interceptor based on the path /jquery/** where path can
       contain jquery and any child hierarchy represented by /**
       e.g. http://localost/springmvc/jquery/firstController
       e.g. http://localost/springmvc/jquery/secondController
       e.g. http://localost/springmvc/jquery/thirdController 
       e.g. http://localost/springmvc/jquery/a/b/c/thirdController  
       we can also use /jquery/* in that case it has to be /jquery/*
       and any immediate child path, it will ignore if it is way
       beyond the level 1 hierarchy.
       e.g. http://localost/springmvc/jquery/firstController
       e.g. http://localost/springmvc/jquery/secondController
       e.g. http://localost/springmvc/jquery/thirdController 
       but will not able to intercept any request like                                 
       http://localost/springmvc/jquery/a/b/c/thirdController  
       -->
<interceptors>
  <interceptor>
       <mapping path="/jquery/**" />
       <beans:ref bean="FirstInterceptor"/>
  </interceptor>
</interceptors>

Question : Can we declare multiple interceptors?
Answer : Yes we can and we can also refer to the same interceptor for multiple declarations.

<interceptors>
       <interceptor>
              <mapping path="/jquery/**" />
              <beans:ref bean="FirstInterceptor" />
       </interceptor>
       <interceptor>
              <mapping path="/employee/**" />
              <beans:ref bean="FirstInterceptor" />
       </interceptor>
</interceptors>

Question : Can we have multiple mapping path for the same interceptor.
Answer : Yes above example can be shortened if we have common interceptor for the same path.

<interceptors>
       <interceptor>
              <mapping path="/jquery/**" />
              <mapping path="/employee/**" />
              <beans:ref bean="FirstInterceptor" />
       </interceptor>
</interceptors>

Question : How can we execute or chain the multiple interceptors?
Answer : We can declare multiple interceptor for the same joinpoint or pointcut as follows

<interceptors>
       <!-- First Interceptor for employee/** and /jQuery/** -->
       <interceptor>
              <mapping path="/jquery/**" />
              <mapping path="/employee/**" />
              <beans:ref bean="FirstInterceptor" />
       </interceptor>
       <!-- Second Interceptor for employee/**  -->
       <interceptor>
              <mapping path="/employee/**" />
              <beans:ref bean="SecondInterceptor" />
       </interceptor>
</interceptors>


Question : What is Weaving? What are the different points where weaving can be applied?
Answer : Weaving is the process of linking aspects with other application types or objects to create an advised object. Weaving can be done at compile time, at load time, or at runtime.


Question : Explain XML Schema-based aspect implementation?
Answer : In this implementation case, aspects are implemented using regular classes along with XML based configuration.

Question : Explain annotation-based (@AspectJ based) aspect implementation
Answer : This implementation case (@AspectJ based implementation) refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations.


Spring Model View Controller (MVC)

http://stackoverflow.com/questions/755563/what-design-patterns-are-used-in-spring-framework

Question : What is Spring MVC framework?
Answer : 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 a clean separation of controller logic from business objects. It also allows to declaratively bind request parameters to business objects.


Question : What is DispatcherServlet?
Answer : The Spring Web MVC framework is designed around a DispatcherServlet that handles all the HTTP requests and responses.


Question : How to activate Dispatcher servlet in the web application?
Answer : We have to declare the servlet in the web.xml, like as follows : 
<servlet>
       <servlet-name>appServlet</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
       <servlet-name>appServlet</servlet-name>
       <url-pattern>/</url-pattern>
</servlet-mapping>

Question : Can you talk about the spring mvc flow?
Answer : following is the step by step flow.
1. Accept the incoming request, based on the url mapping, most of the time it will be just "/" if the application is not handling any other servlet.
2. Incoming request will be prepared and will try find the appropriate handler, which is by default the classes annotated with the @Controller.
3. After identifying the appropriate handler, the dispatcher servlet will give control to the identified controller for the execution process to start, with that it will see if there are some interceptors involve so prehandle and postHandle methods will be called.
4. Preparing the model and identifying the view.
5. Returns the ModelAndView
6. Next is rendering of the view starts along with the model, by using appropriate template technology.
7. Now control is given back to DispatcherServlet.
8. Now response is returned by the DispatcherServlet.

Question : What is the diff between  <context:annotation-config> and <context:component-scan>?
Answer : Following are the diff between both the tags.
1) First big difference between both tags is that <context:annotation-config> is used to activate applied annotations in already registered beans in application context. Note that it simply does not matter whether bean was registered by which mechanism e.g. using <context:component-scan> or it was defined in application-context.xml file itself.

2) Second difference is driven from first difference itself. It does register the beans in context + it also scans the annotations inside beans and activate them. So <context:component-scan> does what <context:annotation-config> does, but additionally it scan the packages and register the beans in application context. 


Question : What is the use of <mvc:annotation-driven/>: ?
Answer This tells the Spring Framework to support annotations like @Controller, @RequestMapping, and others, all of which simplify the writing and configuration of controllers.

Question : What is InternalResourceViewResolver
Answer : InternalResourceViewResolver: The Spring MVC framework supports different types of views for presentation technologies, including JSPs, HTML, PDF, JSON, and so on. When the DispatcherServlet class defined in the application's web.xml file receives a view name returned from the handler, it resolves the logical view name into a view implementation for rendering.

Question : What is WebApplicationContext?
Answer : The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes, and that it knows which servlet it is associated with.
 

Question : What is Controller in Spring MVC framework?
Answer : Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers.
 

Question : What is @Controller annotation
Answer : The @Controller annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API.
 

Question : What is @RequestMapping annotation
Answer : @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.


Question : What is consumes in the @RequestMapping annotation.
Answer The consumable media types of the mapped request, narrowing the primary mapping.
The format is a single media type or a sequence of media types, with a request only mapped if the Content-Type matches one of these media types.
Examples:
 consumes = "text/plain"
 consumes = {"text/plain", "application/*"}
 
Expressions can be negated by using the "!" operator, as in "!text/plain", which matches all requests with a Content-Type other than "text/plain". Supported at the type level as well as at the method level! When used at the type level, all method-level mappings override this consumes restriction.

Question : What is the method attribute in the @RequestMapping?
Answer : The consumable media types of the mapped request, narrowing the primary mapping.
The format is a single media type or a sequence of media types, with a request only mapped if the Content-Type matches one of these media types.
Examples:
 consumes = "text/plain"
 consumes = {"text/plain", "application/*"}
 
Expressions can be negated by using the "!" operator, as in "!text/plain", which matches all requests with a Content-Type other than "text/plain". Supported at the type level as well as at the method level! When used at the type level, all method-level mappings override this consumes restriction.

Question : What is produces attribute in the @RequestMapping?
Answer : The producible media types of the mapped request, narrowing the primary mapping.
The format is a single media type or a sequence of media types, with a request only mapped if the Accept matches one of these media types. Examples:
 produces = "text/plain"
 produces = {"text/plain", "application/*"}
 
Expressions can be negated by using the "!" operator, as in "!text/plain", which matches all requests with a Accept other than "text/plain". Supported at the type level as well as at the method level! When used at the type level, all method-level mappings override this consumes restriction.

Question : What are the possible argument type of the method/handler method annotated with the @RequestMapping.
Answer : Handler methods which are annotated with @RequestMapping annotation are allowed to have very flexible signatures. They may have arguments of the following types, in arbitrary order (except for validation results, which need to follow right after the corresponding command object, if desired):



Question : What will happen if we annotate two method with the @RequestMapping having same value i.e. URL value?
Answer : Bean container will fail to start and will give error as there are two bean method with the same URL Mapping. 

Question : What will happen if we annotate a method with the @RequestMapping without having any URL value?

Answer It will be treated as @RequestMapping(value="", method=RequestMethod.GET)

@RestController
@RequestMapping(value="ExperimentController")
public class ExperimentController {
        @RequestMapping(value="", method=RequestMethod.GET)
        @ResponseBody
        public String experimentOne(){
                return "hello";
        }
}

Hence if you hit the URL like "http://localhost:9090/springmvc/ExperimentController", you will get the response as hello.

Question : What will happen if we annotate two method with the @RequestMapping without having any URL value?
Answer :  Both the method will be treated as @RequestMapping(value="", method=RequestMethod.GET), but we will get the exception while starting of the spring web application container, as the same url is bind to multiple methods.

Question : is it required to prefix the @RequestMapping value with the "/"?
Answer : not it's not unless we want to have hirarchal namespace like rest/reports, so here if we just need "rest" then we can mention just "rest" it is not mandatory to specify like "/rest".

Question : Can we refer to the same controller method with the different URL Patterns?
Answer : It's very much possible, look at the below example.

@RestController
@RequestMapping(value="ExperimentController")
public class ExperimentController {
        @RequestMapping(value={"1","2","3"}, method=RequestMethod.GET)
        @ResponseBody
        public String experimentOne(){
                return "hello";
        }
}
Now we can refer or call the experimentOne method by hitting below urls
http://localhost:9090/springmvc/ExperimentController/1
http://localhost:9090/springmvc/ExperimentController/2
http://localhost:9090/springmvc/ExperimentController/3

Question : Can a controller method serve more than one type of request method type?
Answer : Yes it can be done easily by adding the array of RequestMethod with the method attribute e.g look at below code for more clarity.
@RestController
@RequestMapping(value="ExperimentController")
public class ExperimentController {
        @RequestMapping(value={"1","2","3"}, method={RequestMethod.POST, RequestMethod.GET})
        @ResponseBody
        public String experimentOne(){
                return "hello";
        }
}


Question : What is DispatcherServlet and ContextLoaderListener?
Answer : Spring’s web MVC framework is, like many other web MVC frameworks, request-driven, designed around a central Servlet that handles all the HTTP requests and responses. Spring’s DispatcherServlet however, does more than just that. It is completely integrated with the Spring IoC container so it allows you to use every feature that Spring has.


After receiving an HTTP request, DispatcherServlet consults the HandlerMapping (configuration files) to call the appropriate Controller. The Controller takes the request and calls the appropriate service methods and set model data and then returns view name to the DispatcherServlet. The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request. Once view is finalized, The DispatcherServlet passes the model data to the view which is finally rendered on the browser.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
       id="WebApp_ID" version="3.0">


       <!-- Processes application requests -->
       <servlet>
       <servlet-name>appServlet</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
              <load-on-startup>1</load-on-startup>
       </servlet>

       <servlet-mapping>
              <servlet-name>appServlet</servlet-name>
              <url-pattern>/</url-pattern>
       </servlet-mapping>

</web-app>
By default, DispatcherServlet loads its configuration file using <servlet_name>-servlet.xml. E.g. with above web.xml file, DispatcherServlet will try to find appServlet-servlet.xml file in classpath.
ContextLoaderListener reads the spring configuration file (with value given against “contextConfigLocation” in web.xml), parse it and loads the beans defined in that config file.
It basically bootstrap listener to start up and shut down Spring's root WebApplicationContext. Simply delegates to ContextLoader as well as to ContextCleanupListener. This listener should be registered after Log4jConfigListener in web.xml, if the latter is used.

Question : Difference between <context:annotation-config> vs <context:component-scan>?
Answer : 
1) First big difference between both tags is that <context:annotation-config> is used to activate applied annotations in already registered beans in application context. Note that it simply does not matter whether bean was registered by which mechanism e.g. using <context:component-scan> or it was defined in application-context.xml file itself.

2) Second difference is driven from first difference itself. It registers the beans defined in config file into context + it also scans the annotations inside beans and activate them. So <context:component-scan> does what <context:annotation-config> does, but additionally it scan the packages and register the beans in application context.

Question : Among two DefaultAnnotationHandlerMapping and RequestMappinghandlerMapping, which one is by default and how to use the non default one?
Answer : The mapping is in the controller definition, and we need an instance of a HandlerMapping to interpret these mappings. There are two implementations that can help us out here: the org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping and the org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping. The first is one of the defaults registered by the org.springframework.web.servlet.DispatcherServlet. The second is one of the defaults registered by Spring @MVC (which we can enable with the org.springframework.web .servlet.config.EnableWebMvc annotation or add <mvc:annotation:driven> in the configuration xml file) .


Question : Difference between @Component, @Controller, @Repository & @Service annotations?
Answer : 
1) The @Component annotation marks a java class as a bean so the component-scanning mechanism of spring can pick it up and pull it into the application context. To use this annotation, apply it over class as below:

@Component
public class EmployeeDAOImpl implements EmployeeDAO {
    ...
}

2) The @Repository annotation is a specialization of the @Component annotation with similar use and functionality. In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.

3) The @Service annotation is also a specialization of the component annotation. It doesn’t currently provide any additional behavior over the @Component annotation, but it’s a good idea to use @Service over @Component in service-layer classes because it specifies intent better.

4) @Controller annotation marks a class as a Spring Web MVC controller. It too is a @Component specialization, so beans marked with it are automatically imported into the DI container. When you add the @Controller annotation to a class, you can use another annotation i.e. @RequestMapping; to map URLs to instance methods of a class.

Question : What is @RequestParam?
Answer : Annotation which indicates that a method parameter should be bound to a web request parameter. Supported for annotated handler methods in Servlet and Portlet environments.
If the method parameter type is Map and a request parameter name is specified, then the request parameter value is converted to a Map assuming an appropriate conversion strategy is available.
If the method parameter is Map<String, String> or MultiValueMap<String, String> and a parameter name is not specified, then the map parameter is populated with all request parameter names and values.
defaultValue : The default value to use as a fallback when the request parameter value is not provided or empty. Supplying a default value implicitly sets required() to false.
required : Whether the parameter is required. Default is true, leading to an exception thrown in case of the parameter missing in the request. Switch this to false if you prefer a null in case of the parameter missing. Alternatively, provide a defaultValue, which implicitly sets this flag to false.
value : The name of the request parameter to bind to.


Question : What does the ViewResolver class?
Answer : ViewResolver is an interface to be implemented by objects that can resolve views by name. There are plenty of ways using which you can resolve view names. These ways are supported by various in-built implementations of this interface. Most commonly used implementation is InternalResourceViewResolver class. It defines prefix and suffix properties to resolve the view component.
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <beans:property name="prefix" value="/WEB-INF/views/" />
       <beans:property name="suffix" value=".jsp" />
</beans:bean>
So with above view resolver configuration, if controller method return “login” string, then the “/WEB-INF/views/login.jsp” file will be searched and rendered.

Question : What is a MultipartResolver and when its used?
Answer : Spring comes with MultipartResolver to handle file upload in web application. There are two concrete implementations included in Spring:

CommonsMultipartResolver for Jakarta Commons FileUpload
StandardServletMultipartResolver for Servlet 3.0 Part API
To define an implementation, create a bean with the id “multipartResolver” in a DispatcherServlet’s application context. Such a resolver gets applied to all requests handled by that DispatcherServlet.

If a DispatcherServlet detects a multipart request, it will resolve it via the configured MultipartResolver and pass on a wrapped HttpServletRequest. Controllers can then cast their given request to the MultipartHttpServletRequest interface, which permits access to any MultipartFiles.

Question : How does Spring MVC provide validation support?
Answer : Spring supports validations primarily into two ways.
Using JSR-303 Annotations and any reference implementation e.g. Hibernate Validator
Using custom implementation of org.springframework.validation.Validator interface
In next question, you see an example about how to use validation support in spring MVC application.

Question : How to validate form data in Spring Web MVC Framework?
Answer : Spring MVC supports validation by means of a validator object that implements the Validator interface. You need to create a class and implement Validator interface. In this custom validator class, you use utility methods such as rejectIfEmptyOrWhitespace() and rejectIfEmpty() in the ValidationUtils class to validate the required form fields.

@Component
public class EmployeeValidator implements Validator
{
    public boolean supports(Class clazz) {
        return EmployeeVO.class.isAssignableFrom(clazz);
    }

    public void validate(Object target, Errors errors)
    {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "error.firstName", "First name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "error.lastName", "Last name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.email", "Email is required.");
    }
}
If any of form fields is empty, these methods will create a field error and bind it to the field. The second argument of these methods is the property name, while the third and fourth are the error code and default error message.

To activate this custom validator as a spring managed bean, you need to do one of following things:

1) Add @Component annotation to EmployeeValidator class and activate annotation scanning on the package containing such declarations.


<context:component-scan base-package="com.howtodoinjava.demo" />
2) Alternatively, you can register the validator class bean directly in context file.


<bean id="employeeValidator" class="com.howtodoinjava.demo.validator.EmployeeValidator" />
Read More : Spring MVC Custom Validator and JSR-303 Annotations Examples

Question : What is Spring MVC Interceptor and how to use it?
Answer : As you know about servlet filters that they can pre-handle and post-handle every web request they serve — before and after it’s handled by that servlet. In the similar way, you can use HandlerInterceptor interface in your spring mvc application to pre-handle and post-handle web requests that are handled by Spring MVC controllers. These handlers are mostly used to manipulate the model attributes returned/submitted they are passed to the views/controllers.

A handler interceptor can be registered for particular URL mappings, so it only intercepts requests mapped to certain URLs. Each handler interceptor must implement the HandlerInterceptor interface, which contains three callback methods for you to implement: preHandle(), postHandle() and afterCompletion().

Problem with HandlerInterceptor interface is that your new class will have to implement all three methods irrespective of whether it is needed or not. To avoid overriding, you can use HandlerInterceptorAdapter class. This class implements HandlerInterceptor and provide default blank implementations.


Question : How to handle exceptions in Spring MVC Framework?
Answer : In a Spring MVC application, you can register one or more exception resolver beans in the web application context to resolve uncaught exceptions. These beans have to implement the HandlerExceptionResolver interface for DispatcherServlet to auto-detect them. Spring MVC comes with a simple exception resolver for you to map each category of exceptions to a view i.e. SimpleMappingExceptionResolver to map each category of exceptions to a view in a configurable way.

Let’s say we have an exception class i.e. AuthException. And we want that everytime this exception is thrown from anywhere into application, we want to show a pre-determined view page /WEB-INF/views/error/authExceptionView.jsp. So the configuration would be.

<beans:bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<beans:property name="exceptionMappings">
       <beans:props>
       <beans:prop key="com.howtodoinjava.demo.exception.AuthException">error/authExceptionView</beans:prop>
       </beans:props>
</beans:property>
<beans:property name="defaultErrorView" value="error/genericView" />
</beans:bean>

The “defaultErrorView” property can be configured to show a generic message for all other exceptions which are not configured inside “exceptionMappings” list.

Question : How to achieve localization in Spring MVC applications?
Answer : Spring framework is shipped with LocaleResolver to support the internationalization and thus localization as well. To make Spring MVC application supports the internationalization, you will need to register two beans.

1) SessionLocaleResolver : It resolves locales by inspecting a predefined attribute in a user’s session. If the session attribute doesn’t exist, this locale resolver determines the default locale from the accept-language HTTP header.
<beans:bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
    <beans:property name="defaultLocale" value="en" />
</beans:bean>

2) LocaleChangeInterceptor : This interceptor detects if a special parameter is present in the current HTTP request. The parameter name can be customized with the paramName property of this interceptor. If such a parameter is present in the current request, this interceptor changes the user’s locale according to the parameter value.

<beans:bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <beans:property name="paramName" value="lang" />
</beans:bean>

<!-- Enable the interceptor -->
<beans:bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <beans:property name="interceptors">
        <beans:list>
            <beans:ref bean="localeChangeInterceptor" />
        </beans:list>
    </beans:property>
</beans:bean>
Next step is to have each locale specific properties file having texts in that locale specific language e.g. messages.properties and messages_zh_CN.properties etc.

Question : How to get ServletContext and ServletConfig object in a Spring Bean?
Answer: Simply implement ServletContextAware and ServletConfigAware interfaces and override below methods.


@Controller
@RequestMapping(value = "/magic")
public class SimpleController implements ServletContextAware, ServletConfigAware {

    private ServletContext context;
    private ServletConfig config;

    @Override
    public void setServletConfig(final ServletConfig servletConfig) {
        this.config = servletConfig;

    }

    @Override
    public void setServletContext(final ServletContext servletContext) {
        this.context = servletContext;
    }
   
    //other code
}

Question : How to use Tomcat JNDI DataSource in Spring Web Application?
Answer : For using servlet container configured JNDI DataSource, we need to configure it in the spring bean configuration file and then inject it to spring beans as dependencies. Then we can use it with JdbcTemplate to perform database operations.
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/MySQLDB"/>
</bean>

Question : How to make an ajax call using jQuery for the spring MVC application and get the response in form of JSON?
Answer : Basic steps to be followed for activating the ajax for spring mvc.

Step 1 : Activate jQuery and create method which can make a ajax call.
<!-- Activating jQuery -->
<script   src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<!-- Creating method for making an ajax call -->
<script type="text/javascript">
function ajaxSubmit(){
       //this is to get all the form data
       var params = $('#findContactForm').serialize();
       //Spring mvc requestmapping annotated method name
       var actionMethodName = 'findContactSubmit'
       //Now making an ajax call
       $.getJSON(actionMethodName+'?'+params, function(data){
              //if response is in form of json,
              //then we can directly get the data by call data.propertyName
              //e.g. look at the below example
              alert(data.firstName);
              alert(data.lastName);
       });
}
</script>

Step 2: Create a for in the jsp which has fields and button to call the ajaxfunction declared in the first step.
<form method="POST" action="findContactSubmit" name="findContactForm" id="findContactForm">
<fieldset>
<legend >Contact Form</legend>
<table>
<tr><td>First Name</td><td><input type="text" id="firstName" name="firstName"/></td></tr>
<tr><td>Last Name</td><td><input type="text" id="lastName" name="lastName"/></td></tr>
<tr><td><button type="button" onclick="ajaxSubmit()">Submit</button></td></tr>
</table>
</fieldset>
</form>

Step 3 : Activate the jackson for JSON marshalling and unmarshalling, it's very easy just add the jackson 2 jars in the classpath, alternatively if you have maven project then add the dependency in the pom.xml file.
<dependency>
       <groupId>com.fasterxml.jackson.core</groupId>
       <artifactId>jackson-core</artifactId>
       <version>2.0.4</version>
</dependency>
<dependency>
       <groupId>com.fasterxml.jackson.core</groupId>
       <artifactId>jackson-databind</artifactId>
       <version>2.0.4</version>
</dependency>

Step 4: Spring mvc metho needed to be annotated with the @RequestMapping and @ResponseBody, like the following and it should return an Object or desired object which will be later converted to the json format.

@RequestMapping(value="findContactSubmit", method = RequestMethod.GET)
@ResponseBody
public Object findContactSubmit(HttpServletRequest request){
       Contact contact = new Contact();
       contact.setFirstName("Vikash");
       contact.setLastName("Mishra");
       return contact;
}

Question : How to fix the recursive or infinite conversion of the hibernate entity class object by Jackson,  which has bidirectional relation ship i.e. parent child relation ship for that it is trying to call the each other recursively i.e. Parent has getChilds and each Child is having getParent which in turn result the same Parent and then again getChild()  will get called upon that, during the conversion using Jackson?
Answer : Basically there are three methods,
Method 1 : Add the annotation @JsonIgnore above the child class getter method.

Method 2: another option is to create a pair of the @JsonManagedReference which says that this is parent entity, and go to the next class and add the @JsonBackReference above the parent reference getter or variable.

Method 3 : Which is helpful for the scenario when the we want to start from the child but we are also interested to know the parents of it, in that scenario above two may not help so we have to annotate the class with the following annotation to avoid recursion and also get the parents also.
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id").


Question : How to use use @RequestBody give the example code.
Step 1 :  Create the pojo class which can be mapped to the incoming json request.
public class UserVo {
private String alpha;

public String getAlpha() {
       return alpha;
}
public void setAlpha(String alpha) {
       this.alpha = alpha;
}
}

Step 2 : Create the controller method and annotate the argument with the @RequestBody.
@RequestMapping(value="/responseAjax")  
public String responseAjax(@RequestBody UserVo userVo){
       System.out.println(userVo.getAlpha());  
       return "jquery/entries-a";
}

Step 3: If you are using jQuery then make the following call using the $.ajax, rest of the other ajax method in jQuery was not working as they are sending the data either not in POST like $.getJSON send the data using the GET method, similarly we have load which sends the data as object but still it was not sent as JSON, it got converted as name value pair. So we have to rely on $.ajax() where we can mention the

$(document).ready(function() {
    $('.letters').click( function(event){
        event.preventDefault();
        var obj = {};
        obj.alpha = "A";
        $.ajax({
          type: "post",
          url: "responseAjax", //your valid url
          //this is required for spring 3 - ajax to work (at least for me)
          contentType: "application/json",
          data: JSON.stringify(obj), //json object or array of json objects
          success: function(result) {
                $('#dictionary').html(result);
          },
          error: function(){
              alert('failure');
          }
       });
   });
})

So here two lines are very important.
contentType: "application/json",
data: JSON.stringify(obj), //json object or array of json objects


Question  :  How to configure transaction management in spring?
Answer : One of the most important to configuring the transaction manager is configure persistence context by creating the file name persistence.xml and placing in the META-INF folder. Below is the basic configuration.
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">
    <!-- Will be referenced in Spring Context File -->
    <persistence-unit name="jpa-persistence" transaction-type="RESOURCE_LOCAL">
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:xe" />
            <!-- User name and Password-->
            <property name="javax.persistence.jdbc.user" value="HR" />
            <property name="javax.persistence.jdbc.password" value="password" />
            <!-- Dialect name e.g. the oracle driver for the oracle db -->
            <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver" />
            <!-- <property name="hibernate.show_sql" value="true"/> -->
        </properties>
    </persistence-unit>
</persistence>

Now next step is to configure in spring
<!-- Define Hibernate JPA Vendor Adapter -->
<beans:bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    <beans:property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect" />
</beans:bean>  

<!-- Entity Manager Factory -->
<beans:bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
    <beans:property name="persistenceUnitName" value="jpa-persistence"></beans:property>
    <beans:property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</beans:bean>

<!-- Transaction Manager -->
<beans:bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <beans:property name="entityManagerFactory" ref="entityManagerFactory" />
</beans:bean>

<!-- Activating the transaction manager based on annotation -->    
<tx:annotation-driven transaction-manager="transactionManager"/>


Next is create a class annotated with the Repository to signify that the given class is meant for database transaction.

@Repository(value="tempDao")
public class TempDao {
  //Injecting the Entity Manager
  @PersistenceContext
  EntityManager em;
  //Adding the @Transactional annotating to activate the transaction for the given method.
  @Transactional(value= TxType.REQUIRES_NEW)
       public void saveTemp(Temp temp){ 
              Temp tempd = em.find(Temp.class, temp.getTempId());
              if(tempd != null){
                     em.merge(temp);
              }else{
                     em.persist(temp);
              }            
       }
}

Question : How to create rest web service with the uri template?
Answer : We need to annotate @RequestMapping and the template along with the url and then bind the incoming template value with the method argument by using @PathVariable.
E.g.
Creating the Rest Web service
@RestController
@RequestMapping(value="ExperimentController")
public class ExperimentController {
        @RequestMapping(value="1/{id}", method={RequestMethod.POST, RequestMethod.GET})
        public String experimentOne(@PathVariable("id") String id){
                return "hello   = "+id;
        }
}

To validate this we are going to create a rest client using another technology resteasy which is jax-rs 2.0 implementation.
public class RestEasyClient {
        public static void main(String[] args) {
                //creating client
                Client client = ClientBuilder.newClient();     
                //providing the entire resource url
                WebTarget wClient = client.target("http://localhost:9090/springmvc/ExperimentController/1/{id}");
                //resolving the
                wClient = wClient.resolveTemplate("id", "vikash");
                //calling the web service
                String responsestr = wClient.request("text/plain").get(String.class);          
                System.out.println(responsestr);               
        }
}

Question : Give an example of Consuming and Producing the xml.
Answer : Create a class annotated with the JAXB annotation.
@XmlRootElement(name="root")
public class XMLClass {
        private String name;
        @XmlElement
        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }

        @Override
        public String toString() {
                return "XMLClass [name=" + name + "]";
        }      
}


Now create the RestController with the method having consume attribute and produce attribute having mediatype as application/xml.

@RestController
@RequestMapping(value = "ExperimentController")
public class ExperimentController {
        @RequestMapping(value = "1/{id}", method = { RequestMethod.POST,
                        RequestMethod.GET }, consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE)
        public XMLClass consumingAndProducingXML(@PathVariable("id") String id,
                        @RequestBody XMLClass xmlClass) {
                System.out.println("called the services" + xmlClass);
                return xmlClass;
        }
}

Now let's create the client written using RestEasy
public class RestEasyClient {
        public static void main(String[] args) {
                Entity<String> entity = Entity.entity("", MediaType.APPLICATION_XML);
                // creating client
                Client client = ClientBuilder.newClient();
                // providing the entire resource url
                WebTarget wClient = client
                                .target("http://localhost:9090/springmvc/ExperimentController/1/{id}");
                // resolving the
                wClient = wClient.resolveTemplate("id", "vikash");
                Response response = wClient
                                .request MediaType.APPLICATION_XML)
                                .accept(MediaType.APPLICATION_XML)
                                .post(Entity
                                                .xml("<?xml version=\"1.0\" encoding=\"UTF-8\" "
                                                                + "standalone=\"yes\"?>"
                                                                + "<root><name>Hazel Wood</name>"
                                                                + "</root>"));
                // calling the web service
                System.out.println(response.readEntity(String.class));
        }
}


TODO Section
1. What is resttemplate?

Useful Links
http://www.baeldung.com/mockito-spy
http://eddumelendez.github.io/blog/2015/08/01/spring-4-2-0-springclassrule-and-springmethodrule/
http://www.petrikainulainen.net/software-development/design/why-i-changed-my-mind-about-field-injection/
http://www.javaenthusiasm.com/build-rest-endpoints-in-spring-mvc-controller/
http://frameworkonly.com/browser-back-button-problem/
http://blog.dreamix.eu/webothers/configuring-google-as-oauth2-authorization-provider-in-spring-boot
http://memorynotfound.com/spring-redis-application-configuration-example/
http://java-simo.blogspot.in/
http://frameworkonly.com/spring-boot-crud-tutorial-thymeleaf-spring-data-jpa-hikaricp/
http://www.journaldev.com/8748/spring-4-mvc-security-managing-roles-example-with-in-memorywithout-web-xml-and-without-spring-xml-configuration

Comments

Post a Comment

Popular posts from this blog

NodeJS

Question : Why You should use Node JS? Answer :  Following are the major factor influencing the use of the NodeJS Popularity : The popularity can be important factor, as it has more user base and hence solution  of any common problem faced by developer can found easily online, without any professional help. JavaScript at all levels of the stack :  A common language for frontend and backend offers several potential benefits: The same programming staff can work on both ends of the wire Code can be migrated between server and client more easily Common data formats (JSON) exist between server and client Common software tools exist for server and client Common testing or quality reporting tools for server and client When writing web applications, view templates can be used on both sides Leveraging Google's investment in V8 Engine. Leaner, asynchronous, event-driven model Microservice architecture Question : example of node JS code? Answer :  const fs = require('fs'); const uti

Kubernetes

What is Kubernetes? Kubernetes is a portable, extensible, open-source platform for managing containerized workloads and services, that facilitates both declarative configuration and automation. It has a large, rapidly growing ecosystem.  The name Kubernetes originates from Greek, meaning helmsman or pilot. Google open-sourced the Kubernetes project in 2014. Kubernetes combines over 15 years of Google’s experience running production workloads at scale with best-of-breed ideas and practices from the community. Why you need Kubernetes and what it can do? Containers are a good way to bundle and run your applications. In a production environment, you need to manage the containers that run the applications and ensure that there is no downtime. For example, if a container goes down, another container needs to start. Wouldn’t it be easier if this behavior was handled by a system? That’s how Kubernetes comes to the rescue! Kubernetes provides you with a framework to run distributed systems resi