Saturday, September 6, 2014

Spring IQ

Spring beans are thread safe?
Not automatically. If you expect an instance of your class to be used in the context of multiple threads, you'll need to design it to be thread-safe.

A singleton bean in spring exists per context. It means, if you've multiple contexts, then you may have multiple instances of these singleton objects.

Rules for thread-safety:
1. Don't use states on Controllers, Service Layer Objects, DAOs. (Best practice)
2. If you can't avoid - first rethink your design or - use synchronized.
3. If you want to use prototype scoped beans, be aware of instance explosion.
http://www.bagdemir.com/2012/03/06/thread-safety-in-spring-ioc-while-developing-web-applications-with-spring-mvc/

use ThreadLocal

Always start with Immutable beans. Injection through constructors only and NO Setters. It's the cheapest thread safety you can get.


1: What is Spring?
A: Spring is a multi tier open source lightweight application framework, addressing most infrastructure concerns of enterprise applications. It is mainly a technology dedicated to enable us to build application using POJOs(Plain Old Java Objects).
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 J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.

2: what are benefits/features of using spring?
A: Following is the list of few of the great benefits of using Spring Framework:
·         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 using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
  • Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating 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 such as Struts or other over engineered or less popular web frameworks.
  • Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).
  • Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
3: What are the different modules in Spring framework?
A: Following are the modules of the Spring framework:

·         Spring core container (IOC)
·         AOP Module
·         JDBC & DAO (Spring DAO support and Spring JDBC abstraction framework)
·         ORM (Spring template implementation for Hibernate, JPA, TopLink, JDO, OJB and iBatis)
·         JEE(Spring Remoting JMX, JMS, Email, EJB, RMI, Hessian Burlap, Web Services)
·         Web( Spring Web MVC Framework, Support for other web Frameworks Integration like struts, webworks, Tapestry,JSF  Rich view support, JSP, Velocity, FreeMarker, PDF, Jasper Reports Excel and Spring Portal MVC).

  • 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
4: What is Spring configuration file?
A: Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.

5: What is Dependency Injection?
A: Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways and Dependency Injection is merely one concrete example of Inversion of Control.
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.
A: The process of injecting(pushing) the dependencies into an object is known as DI. This gives some benefits described below.
·         The application development will become faster.
·         Dependency will be reduced.
·         DI Provides proper test environment for the application as it is much easier to isolate the code under test.
6: What are the different types of IoC (dependency injection)?
A: Types of IoC are:
  • 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.
7: Which DI would you suggest Constructor-based or setter-based DI?
A: Since you can mix both, Constructor- and Setter-based DI, it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. Note that the use of a @Required annotation on a setter can be used to make setters required dependencies.

8: What are the benefits of IOC?
A: The main benefits of IOC or dependency injection are:
  • It minimizes the amount of code in your application.
  • It makes your application easy to test as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases.
  • Loose coupling is promoted with minimal effort and least intrusive mechanism.
  • IOC containers support eager instantiation and lazy loading of services.
9: What is AOP?
A:  AOP is a programming methodology that allows the developer to build the core concerns( that is, primary functionality of the system) without making them aware of secondary requirements by introducing aspects that encapsulate all the secondary requirements logic and the point of execution where they have to be applied. The AOP methodology allows developer to implement the individual concerns in a loosely coupled fashion and weave them to build the final system.
A: Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules.

10: What is Spring IoC container?
A: The Spring IoC creates the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application.

11: What are the types of IoC containers? Explain them.
A: There are two types of IoC containers:
  • Bean Factory container: This is the simplest container providing basic support for DI .The BeanFactory is usually preferred where the resources are limited like mobile devices or applet based applications
  • Spring ApplicationContext Container: This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.
12: Give an example of BeanFactory implementation.
A: The most commonly used BeanFactory implementation is the XmlBeanFactory class. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or application.

13: What are the common implementations of the ApplicationContext?
A: The three commonly used implementation of 'Application Context' are:
  • FileSystemXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor.
  • ClassPathXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.
  • WebXmlApplicationContext: This container loads the XML file with definitions of all beans from within a web application.
14: What are the difference between BeanFactory and ApplicationContext in spring?
A: This one is very popular spring interview question and often asks in entry level interview. ApplicationContext is preferred way of using spring because of functionality provided by it and interviewer wanted to check whether you are familiar with it or not.
ApplicationContext
BeanFactory
Here we can have more than one config files possible
In this only one config file or .xml file
Application contexts can publish events to beans that are registered as listeners
Doesn’t support.
Support internationalization (I18N) messages
It’s not
Support application life-cycle events, and validation.
Doesn’t support.
Support  many enterprise services such JNDI access, EJB integration, remoting
Doesn’t support.










15: What are Spring beans?
A: The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML <bean/> definitions.

16: What does a bean definition contain?
A: The bean definition contains the information called configuration metadata which is needed for the container to know the followings:
  • How to create a bean
  • Bean's lifecycle details
  • Bean's dependencies
17: How do you provide configuration metadata to the Spring Container?
A: There are following three important methods to provide configuration metadata to the Spring Container:
  • XML based configuration file.
  • Annotation-based configuration
  • Java-based configuration

18: How do add a bean in spring application?
A: Check the following 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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="helloWorld" class="com.tutorialspoint.HelloWorld">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>

19: How do you define a bean scope?
A: When defining a <bean> in Spring, you have the option of declaring a scope for that bean. For example, to force Spring to produce a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype. Similar way if you want Spring to return the same bean instance each time one is needed, you should declare the bean's scope attribute to be singleton.

20: What bean scopes does Spring support? Explain them.
A: The Spring Framework supports following five scopes, three of which are available only if you use a web-aware ApplicationContext.
  • singleton: This scopes the bean definition to a single instance per Spring IoC container.
  • prototype: This scopes a single bean definition to have any number of object instances.
  • request: This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
  • session: This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
  • global-session: This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
21: What is default scope of bean in Spring framework?
A: The default scope of bean is Singleton for Spring framework.

22: Are Singleton beans thread safe in Spring Framework?
A: No, singleton beans are not thread-safe in Spring framework.

23: Explain Bean lifecycle in Spring framework?
A: Following is sequence of a bean lifecycle in Spring:
  • Instantiate - First the spring container finds the bean's definition from the XML file and instantiates the bean.
  • Populate properties - Using the dependency injection, spring populates all of the properties as specified in the bean definition.
  • Set Bean Name - If the bean implements BeanNameAware interface, spring passes the bean's id to setBeanName() method.
  • Set Bean factory - If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
  • Pre Initialization - Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
  • Initialize beans - If the bean implements IntializingBean interface,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
  • Post Initialization - If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
  • Ready to use - Now the bean is ready to use by the application.
  • Destroy - If the bean implements DisposableBean , it will call the destroy() method .
24: What are inner beans in Spring?
A: A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean. An inner bean definition does not require a defined id or name; the container ignores these values. It also ignores the scope flag. Inner beans are always anonymous and they are always scoped as prototypes.

25: How can you inject Java Collection in Spring?
A: Spring offers four types of collection configuration elements which are as follows:
  • <list>: This helps in wiring i.e. injecting a list of values, allowing duplicates.
  • <set>: This helps in wiring a set of values but without any duplicates.
  • <map>: This can be used to inject a collection of name-value pairs where name and value can be of any type.
  • <props>: This can be used to inject a collection of name-value pairs where the name and value are both Strings.
26: What is bean auto wiring?
A: 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 your bean by inspecting the contents of the BeanFactory without using <constructor-arg> and <property> elements.

27: What are different Modes of auto wiring?
A: 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 which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring.
  • byName: Autowiring by property name. 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: Autowiring by property datatype. 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. http://www.java4s.com/spring/example-on-spring-autowiring-bytype/
  • constructor: Similar to byType, but type applies to constructor arguments. If there is not exactly
  • autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

28: What are the limitations with autowiring?
A: Limitations of autowiring are:
  • Overriding possibility: You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.
  • Primitive data types: You cannot autowire so-called simple properties such as primitives, Strings, and Classes.
  • Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.

29: Can you inject null and empty string values in Spring?

A: Yes.

30: What is Annotation-based container configuration?
A: 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.

31: How do you turn on annotation wiring?
A: Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file by configuring <context:annotation-config/>.

32: What does @Required annotation mean?
A: The @Required annotation applies to bean property setter methods and it indicates that the affected bean property must be populated in XML configuration file at configuration time otherwise the container throws a BeanInitializationException exception.

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

34: What does @Qualifier annotation mean?
A: There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property, in such case you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired.

35: What are the JSR-250 Annotations? Explain them.
A: Spring has JSR-250 based annotations which include @PostConstruct, @PreDestroy and @Resource annotations.
  • @PostConstruct: This annotation can be used as an alternate of initialization callback.
  • @PreDestroy: This annotation can be used as an alternate of destruction callback.
  • @Resource : This annotation can be used on fields or setter methods. The @Resource annotation takes a 'name' attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics.

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

37: How is event handling done in Spring?
A: Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. So if a bean implements the ApplicationListener, then every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified.

38: Describe some of the standard Spring events.
A: Spring provides the following standard events:
  • ContextRefreshedEvent: This event is published when the ApplicationContext is either initialized or refreshed. This can also be raised using the refresh() method on the ConfigurableApplicationContext interface.
  • ContextStartedEvent: This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. You can poll your database or you can re/start any stopped application after receiving this event.
  • ContextStoppedEvent: This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. You can do required housekeep work after receiving this event.
  • ContextClosedEvent: This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be refreshed or restarted.
  • RequestHandledEvent: This is a web-specific event telling all beans that an HTTP request has been serviced.

39: What is Aspect?
A: 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 (the schema-based approach) or regular classes annotated with the @Aspect annotation (@AspectJ style).

40: What is the difference between concern and cross-cutting concern in Spring AOP?
A: Concern: Concern is behavior which we want to have in a module of an application. Concern may be defined as a functionality we want to implement. Issues in which we are interested define our concerns.
Cross-cutting concern: It's a concern which is applicable throughout the application and it affects the entire application. e.g. logging , security and data transfer are the concerns which are needed in almost every module of an application, hence are cross-cutting concerns.

41: What is Join point?
A: This represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework.

42: What is Advice?
A: This is the actual action to be taken either before or after the method execution. This is actual piece of code that is invoked during program execution by Spring AOP framework.

43: What is Pointcut?
A: This is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns as we will see in our AOP examples.

44: What is Introduction?
A: An introduction allows you to add new methods or attributes to existing classes.

45: What is Target object?
A: The object being advised by one or more aspects, this object will always be a proxy object. Also referred to as the advised object.

46: What is Weaving?
A: Weaving is the process of linking aspects with other application types or objects to create an advised object.

47: What are the different points where weaving can be applied?
A: Weaving can be done at compile time, load time, or at runtime.

48: What are the types of advice?
A: Spring aspects can work with five kinds of advice mentioned below:
  • 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.

49: What is XML Schema based aspect implementation?
A: Aspects are implemented using regular classes along with XML based configuration.

50: What is @AspectJ? based aspect implementation?
A: @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations.

51: How JDBC can be used more efficiently in spring framework?
A: JDBC can be used more efficiently with the help of a template class provided by spring framework called as JdbcTemplate.

52: How JdbcTemplate can be used?
A: With use of Spring JDBC framework the burden of resource management and error handling is reduced a lot. So it leaves developers to write the statements and queries to get the data to and from the database. JdbcTemplate provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling.

53: What are the types of the transaction management Spring supports?
A: 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.

54: Which of the above transaction management type is preferable?
A: 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.

55: What is Spring MVC framework?
A: The Spring web MVC framework provides model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.

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

57: What is WebApplicationContext ?
A: 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.

58: What are the advantages of Spring MVC over Struts MVC ?
A: Following are some of the advantages of Spring MVC over Struts MVC:
  • Spring's MVC is very versatile and flexible based on interfaces but Struts forces Actions and Form object into concrete inheritance.
  • Spring provides both interceptors and controllers, thus helps to factor out common behavior to the handling of many requests.
  • Spring can be configured with different view technologies like Freemarker, JSP, Tiles, Velocity, XLST etc. and also you can create your own custom view mechanism by implementing Spring View interface.
  • In Spring MVC Controllers can be configured using DI (IOC) that makes its testing and integration easy.
  • Web tier of Spring MVC is easy to test than Struts web tier, because of the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.
  • Struts force your Controllers to extend a Struts class but Spring doesn't, there are many convenience Controller implementations that you can choose to extend.
  • In Struts, Actions are coupled to the view by defining ActionForwards within a ActionMapping or globally. SpringMVC has HandlerMapping interface to support this functionality.
  • With Struts, validation is usually performed (implemented) in the validate method of an ActionForm. In SpringMVC, validators are business objects that are NOT dependent on the Servlet API which makes these validators to be reused in your business logic before persisting a domain object to a database.
59: What is Controller in Spring MVC framework?
A: 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.

60: Explain the @Controller annotation.
A: 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.

61: Explain @RequestMapping annotation.
A: @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

62: What are the ways to access Hibernate by using Spring?
A: There are two ways to access hibernate using spring:
  • Inversion of Control with a Hibernate Template and Callback.
  • Extending HibernateDAOSupport and Applying an AOP Interceptor node.

63: What are ORM's Spring supports ?
A: Spring supports the following ORM's :
  • Hibernate
  • iBatis
  • JPA (Java Persistence API)
  • TopLink
  • JDO (Java Data Objects)
  • OJB

1) What is Spring IOC Container?

4) What is Spring Integration?
5) How to call remote method by RMI using Spring
6) What scheduling feature Spring framework provides?
7) How do you make a Singleton bean to lazy load in ApplicationContext which loads all Singleton beans eagerly during startup?
8) Does Spring Security part of Spring framework?
9) How to configure Spring using Annotation
10) Which version of Spring have you used recently and what is difference you observed from previous spring version.

64: What is IOC or inversion of control?
Answer: This Spring interview question is first step towards Spring framework and many interviewer starts Spring interview from this question. As the name implies Inversion of control means now we have inverted the control of creating the object from our own using new operator to container or framework. Now it’s the responsibility of container to create object as required. We maintain one xml file where we configure our components, services, all the classes and their property. We just need to mention which service is needed by which component and container will create the object for us. This concept is known as dependency injection because all object dependency (resources) is injected into it by framework.

Example:
  <bean id="createNewStock" class="springexample.stockMarket.CreateNewStockAccont">
        <property name="newBid"/>
  </bean>
In this example CreateNewStockAccont class contain getter and setter for newBid and container will instantiate newBid and set the value automatically when it is used. This whole process is also called wiring in Spring and by using annotation it can be done automatically by Spring, refereed as auto-wiring of bean in Spring.

65: what is Bean Factory, have you used XMLBeanFactory?
Ans: BeanFactory is factory Pattern which is based on IOC design principles.it is used to make a clear separation between application configuration and dependency from actual code.
XmlBeanFactory is one of the implementation of bean Factory which we have used in our project.
org.springframework.beans.factory.xml.XmlBeanFactory is used to create bean instance defined in our xml file.
BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));
Or
ClassPathResource resorce = new ClassPathResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(resorce);

65: What is difference between singleton and prototype bean?
Ans: This is another popular spring interview questions and an important concept to understand. Basically a bean has scopes which defines their existence on the application
Singleton: means single bean definition to a single object instance per Spring IOC container.
Prototype: means a single bean definition to any number of object instances.
Whatever beans we 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.

  <bean id="createNewStock"     class="springexample.stockMarket.CreateNewStockAccont" singleton=”false”>
        <property name="newBid"/>
  </bean>

66: What type of transaction Management Spring support?
Ans: This spring interview questions is little difficult as compared to previous questions just because transaction management is a complex concept and not every developer familiar with it. Transaction management is critical in any applications that will interact with the database. The application has to ensure that the data is consistent and the integrity of the data is maintained.  Two type of transaction management is supported by spring

1. Programmatic transaction management
2. Declarative transaction management.

67: What is the core container module?
Ans. This module is provided by the fundamental functionality of the spring framework. In this module BeanFactory is the heart of any spring-based application. The entire framework has been built atop this module. This module is what we call the core container module.

68: Give an example of BeanFactory implementation?
Ans. The most common example of BeanFactory implementation is the XmlBeanFactory class. This container contains reads the configuration metadata from an Xml file and uses it to create a fully configured system or application.

69: What is Web Application Context?

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

70: What is DataAccessException?

Ans. DataAccessException is a runtime exception. This is an unchecked exception and the user is not forced to handle this kind of exception.

71: What are the advantages of Spring Framework?
Ans. The advantages of spring are as follows:
  1. Spring has layered architecture. So it is up to the programmer what to use and what to leave.
  2. Spring Enables POJO (Plain old Java object) Programming. POJO programming enables continuous integration and testability.
  3. Dependency Injection and Inversion of Control Simplifies JDBC (Java Database Connectivity), open source and no vendor lock-in.

 

72: What is bean wiring?

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

73. What are the different types of IOC (dependency injection)?
There are three types of dependency injection:
  • Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
  • Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
  • Interface Injection (e.g. Avalon): Injection is done through an interface.
Note: Spring supports only Constructor and Setter Injection

74. What is Bean Factory ?
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
  • BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client.
  • BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.

75. What is Application Context?
A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory. Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
  • A means for resolving text messages, including support for internationalization.
  • A generic way to load file resources.
  • Events to beans that are registered as listeners.

76. What is DelegatingVariableResolver?
Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard Java Server Faces managed beans mechanism which lets you use JSF and Spring together. This variable resolver is called as DelegatingVariableResolver

77. What are the ways to access Hibernate using Spring ?
   There are two approaches to Spring’s Hibernate integration:
  • Inversion of Control with a HibernateTemplate and Callback
  • Extending HibernateDaoSupport and Applying an AOP Interceptor

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

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

80. What are the benefits of the Spring Framework transaction management ?
The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits:
  • Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
  • Supports declarative transaction management.
  • Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
  • Integrates very well with Spring's various data access abstractions.

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

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

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

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

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

89. What is PreparedStatementCreator ?
PreparedStatementCreator:
·         Is one of the most commonly used interfaces for writing data to database.
·         Has one method – createPreparedStatement(Connection)
·         Responsible for creating a PreparedStatement.
·         Does not need to handle SQLExceptions.

 90. What is SQLProvider?
   SQLProvider:
    Has one method – getSql()
    Typically implemented by PreparedStatementCreator implementers.
    Useful for debugging

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

92. When to use Dependency Injections?
There are different scenarios where you Dependency Injections are useful.
·         You need to inject configuration data into one or more component.
·         You need to inject the same dependency into multiple components.
·         You need to inject different implementation of the same dependency.
·         You need to inject the same implementation in different configuration.
·         You need some of the services provided by container.

93. When you should not use Dependency Injection?
There were scenarios where you don’t need dependency injections e.g.
·         You will never need a different implementation.
·         You will never need different configurations.

94. How you will decide when to use prototype scope and when singleton scope bean?
You should use the prototype scope for all beans that are stateful and the singleton scope should be used for stateless beans.

95. How to Call Stored procedure in Spring Framework?
To call a Stored procedure in Spring framework you need to create Class which will should extends StoredProcedure class. Take the example of getting Employee Details by Employee Id. package com.mytest.spring.storeproc
import java.sql.ResultSet;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.StoredProcedure;
public class EmployeeInfo extends StoredProcedure {

                      private static final String EMP_ID = "EMP_ID";
                      private static final String EMP_NAME = "EMP_NAME";
                      private static final String JOIN_DATE = "JOIN_DATE";
                      public SnapshotSearchStoredProcedure(DataSource dataSource, String procedureName)
                      {
                            super(dataSource, procedureName);
                           declareParameter(new SqlParameter(EMP_ID, Types.NUMERIC));
                           declareParameter(new SqlOutParameter(EMP_NAME, Types.VARCHAR));
                           declareParameter(new SqlOutParameter(JOIN_DATE, Types.VARCHAR));
                           compile ();
                      }
                       public Map execute(Integer empId)
                       {
                                  Map<String, Object> inputs = new HashMap<String, Object>();
                                  inputs.put(P_CLD_IDR, empId);
                                  Map<String, Object> result = execute (inputs);
                                  return result;
                       }
}

You just need to call the execute method from the DAO layer.

96. What is IOC?
·         IOC stands for Inversion of Control pattern.
·         It is also called as dependency injection.
·         This concept says that you do not create your objects but describe how they should be created.
·         Similarly, you do not directly connect your components and services together in code but describe which services are needed by which components in a configuration file.
·         A container then hooks them all up.

97. How would you integrate Spring and Hibernate using HibernateDaoSupport?
This can be done through Spring’s SessionFactory called LocalSessionFactory. The steps in integration process are:
a.) Configure the Hibernate SessionFactory
b.) Extend your DAO Implementation from HibernateDaoSupport
c.) Wire in Transaction Support with AOP

98. What are the various transaction manager implementations in Spring?
1. DataSourceTransactionManager : PlatformTransactionManager implementation for single JDBC data sources.
2. HibernateTransactionManager: PlatformTransactionManager implementation for single Hibernate session factories.
3. JdoTransactionManager : PlatformTransactionManager implementation for single JDO persistence manager factories.
4. JtaTransactionManager : PlatformTransactionManager implementation for JTA, i.e. J2EE container transactions. 

99. What is JdbcTemplate in Spring? And how to use it?
The JdbcTemplate class is the main class of the JDBC Core package. The JdbcTemplate (The class internally use JDBC API) helps to eliminate lot of code you write with simple JDBC API (Creating connection, closing connection, releasing resources, handling JDB Exceptions, handle transaction etc.). The JdbcTemplate handles the creation and release of resources, which helps you to avoid common error like forgetting to close connection.
Examples:
1. Getting row count from database.
int rowCount = this.jdbcTemplate.queryForObject("select count(*) from t_employee", int.class);
2. Querying for a String.
String lastName = this.jdbcTemplate.queryForObject( "select last_name from t_employee where Emp_Id = ?", new Object[]{377604L}, String.class);
3. Querying for Object
Employee employee = this.jdbcTemplate.queryForObject( "select first_name, last_name from t_employee where Emp_Id = ?", new Object[]{3778604L}, new RowMapper()
{
public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
Employee employee = new Employee();
employee.setFirstName(rs.getString("first_name"));
employee.setLastName(rs.getString("last_name"));
return employee;
}
});
4. Querying for N number of objects.
List<Employee> employeeList = this.jdbcTemplate.query("select first_name, last_name from t_employee", new RowMapper<Employee>() {
public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
Employee employee = new Employee();
employee.setFirstName(rs.getString("first_name"));
employee.setLastName(rs.getString("last_name"));
return employee;
}
});

100. What NamedParameterJdbcTemplate in Spring?
The NamedParameterJdbcTemplate allow basic set of JDBC operations, it allows named parameter in the query instead of traditional (?) placeholder, the functionality is similar to JdbcTemplate class.
Example:
NamedParameterJdbcTemplate namedParameterJdbcTemplate;
String empInsrtQuery = "INSERT INTO Employee (name, age, salary) VALUES (:name, :age, :salary)";
Map namedParameters = new HashMap();
namedParameters.put("name", name);
namedParameters.put("age", age);
namedParameters.put("salary", salary);
namedParameterJdbcTemplate.update(empInsrtQuery, namedParameters);

101. What is front controller in Spring MVC?
The Front Controller is basically a type of Design pattern which are being implemented in different framework (e.g. Struts and Spring MVC etc.). In Spring MVC DispatcherServlet act as a Front Controller for the framework and responsible for intercepting every request and then dispatches/forwards request to appropriate controller. Configure the DispatcherServlet in the web.xml file of web application and request which we want to be handled by DispatcherServlet should be mapped using URL mapping. For example all requests ending with *.do will be handled by the DispatcherServlet.
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

102. Difference between FileSystemResource and ClassPathResource?
In FileSystemResource you need to give the configuration file (i.e. spring-config.xml) relative to your project or the absolute location of the file.
In ClassPathResource spring looks for the file in the ClassPath so configuration (i.e. spring-config.xml) file should be included in the classpath. If spring-config.xml is in classpath, you can simply give the name of the file.
For Example: If your configuration file is at src/main/java/com/test/loadresource then your FileSystemResource would be:
FileSystemResource resource = new FileSystemResource("src/main/java/com/test/loadresource/spring-config.xml");
And ClassPathResource would be:
ClassPathResource resource = new ClassPathResource("com/test/loadresource /spring-config.xml");


103. What would happen if we have a prototype bean injected into a singleton bean ? How many objects of prototype bean object will be created ?
When a singleton bean is created , a single instance of the prototype bean objecte is created. It won't create a new prototype bean.

104. A bean can be marked abstract by abstract=true, does not that mean we have to make the corresponding java class abstract ?
No, a bean marked abstract makes the bean not instantiable, also it makes an ideal situation to use this reference as parent to other child bean definition. Making the corresponding java as abstract is not necessary but can be done

105. If an inner bean is defined with an id, can you use this id to fetch the bean from the container ?
No, An bean defined inner bean can't be accessed even if the id attribute has value. so getBean("theInnerId") will fail with NoSuchBeanDefinitionException.

106. What is the implementation of List is used when you use the <list> tag in a bean definition ?
How do you use a particular implementation of collection in your bean definition ?
You can use the <util:set> <util:list> and <util:map> with set-class to the implementation you want to use. For example <util:list set-class="java.util.LinkedList"> to use linkedList as implementation, and don't forget to include the schema details in the beans tag. Also util tag can let you create id of the collection , thus this can be referred or shared with any other beans by using the regular way , i.e. the ref tag.

107. What are Lazily-instantiated beans?
A: Spring by default instantiate all beans at startup. This helps in overcoming any problems which came across while instantiating beans at startup only. But sometimes, some beans are not required to be initialized during startup, rather we want them to be initialized in later stages of application. For such beans, we include “lazy-init="true"” while configuring beans.
<bean lazy-init="true">
    <!-- this bean will not be pre-instantiated... -->
</bean>

Q: Does Spring Framework support Transaction context propagation across remote calls?
A: No

Explain the different types of AutoProxying?
BeanNameAutoProxyCreator: This proxy is used to identify beans to proxy through a list of names. It checks the matches that are direct, “xxx” and “*xxx”.
DefaultAdvisorAutoProxyCreator: This proxy is the implementation of BeanPostProcessor which creates AOP proxies. These AOP proxies are based on BeanFactory’s all Candidate Advisors. It is a generic class which does not have a specific code to handle any specific aspects.
Metadata autoproxying: The metadata autoproxy is concerned with the possibility to employ annotations in certain classes, like defining transactions. To configure this type of proxies, the source level metadata interpretation and the bean usage that employs those attributes is done by DefaultAdvisorAutoProxyCreator.

Spring MVC interview questions

1 comment: