• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/86

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

86 Cards in this Set

  • Front
  • Back

What is Spring?

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.

What are benefits of using spring?

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.

What are the different modules in Spring framework?

What is Spring configuration file?

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

What is Dependency Injection?

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.

What are the different types of IoC (dependency injection)?

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.

Which DI would you suggest Constructor-based or setter-based DI?

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.

What are the benefits of IOC?

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.

What is AOP?

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

What is Spring IoC container?

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.

What are types of IoC containers? Explain them.

There are two types of IoC containers:




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

Give an example of BeanFactory implementation.

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.

What are the common implementations of the ApplicationContext?

The four 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.




AnnotationConfigApplicationContext Standalone application context, accepting annotated classes as input - in particular @Configuration - annotated classes, but also plain @Component types and JSR-330 compliant classes

What is the difference between Bean Factory and ApplicationContext?

Following are some of the differences:




Application contexts provide a means for resolving text messages, including support for i18n of those messages.




Application contexts provide a generic way to load file resources, such as images.




Application contexts can publish events to beans that are registered as listeners.




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




ApplicationContext supports automatic BeanPostProcessor and BeanFactoryPostProcessor registration.




Inshort, the BeanFactory provides the configuration framework and basicfunctionality, and the ApplicationContext adds moreenterprise-specific functionality.


Usean ApplicationContext unless you have a good reason for not doing so.

What are Spring beans?

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


What does a bean definition contain?

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

How do you provide configuration metadata to the Spring Container?

There are following three important methods to provide configuration metadata to the Spring Container:




XML based configuration file.


Annotation-based configuration


Java-based configuration

How do add a bean in spring application?

XML class = ...




@Bean cration annotated method in @Configuration annotated class




@Component on the class declaration



How do you define a bean scope?

When defining a 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.




scope = / @Scope / Singleton by default


What bean scopes does Spring support? Explain them.

Singleton(Default)


Scopes a single bean definition to a single object instance perSpring IoC container.



Prototype


Scopesa single bean definition to any number of object instances.



Request


Scopes a single bean definition to the lifecycle of a single HTTPRequest; that is, each HTTP request has its own instance of abean created off the back of a single bean definition. Only validin the context of a web-aware Spring ApplicationContext.



Session


Scopesa single bean definition to the lifecycle of an HTTP Session.Only valid in the context of a web-aware SpringApplicationContext.



GlobalSession


Scopesa single bean definition to the lifecycle of a global HTTPSession. Typically only valid when used in a Portlet context.Only valid in the context of a web-aware SpringApplicationContext.



Application


Scopesa single bean definition to the lifecycle of a ServletContext.Only valid in the context of a web-aware SpringApplicationContext.



Websocket


Scopesa single bean definition to the lifecycle of a WebSocket. Onlyvalid in the context of a web-aware Spring ApplicationContext.


What is default scope of bean in Spring framework?

The default scope of bean is Singleton for Spring framework.

Are Singleton beans thread safe in Spring Framework?

No, singleton beans are not thread-safe in Spring framework.

Explain Bean lifecycle in Spring framework?

Creation:


Read Bean Deffinitions → PostProcessBeanDefinitions →


Instantiation(call constructor) →


Populate properties(containermanaged) →


Aware interfaces (BeanFactoryAware, etc) →


@Postconstruct and other BPPs(pre-initialization) →


InitializationBean.afterPropertiesSet() →


init-method (xml) →


BPPs(post-initialization)




Destruction:


@Predestoy →


DisposableBean.destroy() →


destoy-method(xml)




Donot mix init methods, use only one option, @Postconstruct -@Predestroy is my choice.


What are inner beans in Spring?

An element inside the or 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.


How can you inject Java Collection in Spring?

Spring offers four types of collection configuration elements which are as follows:




This helps in wiring i.e. injecting a list of values, allowing duplicates.




This helps in wiring a set of values but without any duplicates.




This can be used to inject a collection of name-value pairs where name and value can be of any type.




This can be used to inject a collection of name-value pairs where the name and value are both Strings.


What is bean auto wiring?

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 and elements.

What is bean auto wiring?

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. This is what you already have seen in Dependency Injection chapter.




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.




constructor: 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.

What is the difference between


@Autowired @Inject and @Resource annotations?

All of them placed on the field make the same job but in slightly different way.



@Autowired(Spring specific) and @Inject(JSR) firstly tries to find autowiring candidate by Type of the field, if nothing found - exception, if one found - ok, if more then one found they try to resolve ambiguity by name. Both these annotations treated by AutowiredAnotationBPP



@Resource firstly tries to inject field by name and if candidates not found then tries to resolve issue by type matching among registered beans. In second case throws exception if more then one bean of type found. Treated by CommonAnnotationBPP.



Rule: Want byType wiring - use @Autowired


byName - use @Resource

What are the limitations with autowiring?

Limitations of autowiring are:


Overrriding posibility: You can still specify dependencies using and 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.


Can you inject null and empty string values in Spring?

Yes.

What is Annotation-based container configuration?

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.

How do you turn on annotation wiring?

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 .

What does @Required annotation mean?

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.

What does @Autowired annotation mean?

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.

What does @Qualifier annotation mean?

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.

What are the JSR-250 Annotations? Explain them.

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.

What is Spring Java Based Configuration? Give some annotation example.

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.

How is event handling done in Spring?

Event handling in the ApplicationContext is provided through theApplicationEvent 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.

Describe some of the standard Spring events.

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.

What is Aspect?

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

What is the difference between concern and cross-cutting concern in Spring AOP?

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.

What is Join point?

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.

What is Advice?

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.

What is Pointcut?

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.

What is Introduction?

An introduction allows you to add new methods or attributes to existing classes.

What is Target object?

The object being advised by one or more aspects, this object will always be a proxy object. Also referred to as the advised object.

What is Weaving?

Weaving is the process of linking aspects with other application types or objects to create an advised object.

What are the different points where weaving can be applied?

Weaving can be done at compile time, load time, or at runtime.

What are the types of advice?

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.

What is XML Schema based aspect implementation?

Aspects are implemented using regular classes along with XML based configuration.

What is @AspectJ based aspect implementation?

@AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations.

How JDBC can be used more efficiently in spring framework?

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




How JdbcTemplate can be used?

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.


JdbcTemplate removes plumbing code and helps you concentrate on the SQL query and parameters. You just need to configure it with a DataSource, and you can then write code like this:


int nbRows = jdbcTemplate.queryForObject (


"select count(*) from person", Integer.class);




Person p = jdbcTemplate.queryForObject (


"select first, last from person where id=?",


rs -> new Person(rs.getString(1), rs.getString(2)), 134561351656L);

What are the types of the transaction management Spring supports?

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.

Which of the above transaction management type is preferable?

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.

What is Spring MVC framework?

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.

What is a DispatcherServlet?

The Spring Web MVC framework is designed around a DispatcherServlet that handles all the HTTP requests and responses.

What is WebApplicationContext ?

The WebApplicationContext is an extension of the plain ApplicationContextthat 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.

What are the advantages of Spring MVC over Struts MVC ?

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.

What is Controller in Spring MVC framework?

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.

Explain the @Controller annotation.

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.

Explain @RequestMapping annotation.

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

What is Spring-ORM

Spring-ORM is an umbrella module that covers many persistence technologies, namely JPA, JDO, Hibernate and iBatis. For each of these technologies, Spring provides integration classes so that each technology can be used following Spring principles of configuration, and smoothly integrates with Spring transaction management.


For each technology, the configuration basically consists in injecting a DataSource bean into some kind of SessionFactory or EntityManagerFactory etc. bean.

Benefits of using Spring-ORM with Hibernate?

Easier testing. Spring’s IoC approach makes it easy to swap the implementations and configuration locations of Hibernate SessionFactory instances, JDBCDataSource instances, transaction managers, and mapped object implementations (if needed)




Common data access exceptions.


Spring can wrap exceptions from your ORM tool, converting them from proprietary (potentially checked) exceptions to a common runtime DataAccessException hierarchy.




General resource management. Ex. For Hebernate Spring makes it easy to create and bind a Session to the current thread transparently, by exposing a current Session through the Hibernate SessionFactory.




Integrated transaction management. You can wrap your ORM code with a declarative, aspect-oriented programming (AOP) style method interceptor either through the @Transactional annotation or by explicitly configuring the transaction AOP advice in an XML configuration file

Explain Core Container Spring Module?

TheCore Container consists of the spring-core, spring-beans,spring-context, spring-context-support, and spring-expression (SpringExpression Language) modules.


Thespring-core and spring-beans modules provide the fundamental parts ofthe framework, including the IoC and Dependency Injection features.TheBeanFactory is a sophisticated implementation of the factorypattern. It removes the need for programmatic singletons and allowsyou to decouple the configuration and specification of dependenciesfrom your actual program logic.




TheContext (spring-context) module builds on the solid base provided bythe Core and Beans modules: it is a means to access objects in aframework-style manner that is similar to a JNDI registry. TheContext module inherits its features from the Beans module and addssupport for internationalization (using, for example, resourcebundles), event propagation, resource loading, and the transparentcreation of contexts by, for example, a Servlet container. TheContext module also supports Java EE features such as EJB, JMX, andbasic remoting. The ApplicationContext interface is the focal pointof the Context module. spring-context-support provides support forintegrating common third-party libraries into a Spring applicationcontext for caching (EhCache, Guava, JCache), mailing (JavaMail),scheduling (CommonJ, Quartz) and template engines (FreeMarker,JasperReports, Velocity).




Thespring-expression module provides a powerful Expression Language forquerying and manipulating an object graph at runtime. It is anextension of the unified expression language (unified EL) asspecified in the JSP 2.1 specification. The language supports settingand getting property values, property assignment, method invocation,accessing the content of arrays, collections and indexers, logicaland arithmetic operators, named variables, and retrieval of objectsby name from Spring’s IoC container. It also supports listprojection and selection as well as common list aggregations.


Explain AOP and Instrumentation Spring Modules?

The spring-aop module provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example,method interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated. Using source-level metadata functionality, you can also incorporate behavioral information into your code, in a manner similar to that of .NETattributes.



The separate spring-aspects module provides integration with AspectJ.



The spring-instrument module provides class instrumentation support and classloader implementations to be used in certain application servers. The spring-instrument-tomcat module contains Spring’s instrumentation agent for Tomcat.


Explain Messaging Spring Module?

SpringFramework 4 includes a spring-messaging module with key abstractionsfrom the Spring Integration project such as Message,MessageChannel, MessageHandler, and others to serve as a foundationfor messaging-based applications. The module also includes a set ofannotations for mapping messages to methods, similar to the SpringMVC annotation based programming model.


Explain Data Access/Integration Spring Module?

TheData Access/Integration layer consists of the JDBC, ORM, OXM, JMS,and Transaction modules.


Thespring-jdbc module provides a JDBC-abstraction layer that removes theneed to do tedious JDBC coding and parsing of database-vendorspecific error codes.


Thespring-tx module supports programmatic and declarative transactionmanagement for classes that implement special interfaces and for allyour POJOs (Plain Old Java Objects).


Thespring-orm module provides integration layers for popularobject-relational mapping APIs, including JPA, JDO, and Hibernate.Using the spring-orm module you can use all of these O/R-mappingframeworks in combination with all of the other features Springoffers, such as the simple declarative transaction management featurementioned previously.


Thespring-oxm module provides an abstraction layer that supportsObject/XML mapping implementations such as JAXB, Castor, XMLBeans,JiBX and XStream.




Thespring-jms module (Java Messaging Service) contains features forproducing and consuming messages. Since Spring Framework 4.1, itprovides integration with the spring-messaging module.


Explain Web Spring Module?

TheWeb layer consists of the spring-web, spring-webmvc,spring-websocket, and spring-webmvc-portlet modules.


Thespring-web module provides basic web-oriented integration featuressuch as multipart file upload functionality and the initialization ofthe IoC container using Servlet listeners and a web-orientedapplication context. It also contains an HTTP client and theweb-related parts of Spring’s remoting support.


Thespring-webmvc module (also known as the Web-Servlet module) containsSpring’s model-view-controller (MVC) and REST Web Servicesimplementation for web applications. Spring’s MVC frameworkprovides a clean separation between domain model code and web formsand integrates with all of the other features of the SpringFramework.


Thespring-webmvc-portlet module (also known as the Web-Portlet module)provides the MVC implementation to be used in a Portlet environmentand mirrors the functionality of the spring-webmvc module

Explain Test Spring Module?

Thespring-test module supports the unit testing and integration testingof Spring components with JUnit or TestNG. It provides consistentloading of SpringApplicationContexts and caching of those contexts.It also provides mock objects that you can use to test your code inisolation.


What is the difference between singleton and prototype bean?

Whenyou create a bean definition, you create a recipe for creating actualinstances of the class defined by that bean definition. The idea thata bean definition is a recipe is important, because it means that, aswith a class, you can create many object instances from a singlerecipe.



Difference is that container injects same singleton bean instance in all appropriate places. But when we use prototype scope new instance of object creates every time we inject it.


Also spring stores all the singleten instances interlaly and is able to call pre-destoy or other method during bean destruction. On the other hand prototypes are only created by container and not managed by it after creation.


Explain Singleton scope?

Onlyone shared instance of a singleton bean is managed, and all requestsfor beans with an id or ids matching that bean definition result inthat one specific bean instance being returned by the Springcontainer.




Spring’sconcept of a singleton bean differs from the Singleton pattern asdefined in the Gang of Four (GoF) patterns book. The GoF Singletonhard-codes the scope of an object such that one and only one instanceof a particular class is created per ClassLoader. The scope of theSpring singleton is best described as per container and per bean.This means that if you define one bean for a particular class in asingle Spring container, then the Spring container creates one andonly one instance of the class defined by that bean definition. Thesingleton scope is the default scope in Spring.




Toput it another way, when you define a bean definition and it isscoped as a singleton, the Spring IoC container creates exactly oneinstance of the object defined by that bean definition. This singleinstance is stored in a cache of such singleton beans, and allsubsequent requests and references for that named bean return thecached object.


Explain Prototype scope?

      In
contrast to the other scopes, Spring does not manage the complete
lifecycle of a prototype bean: the container instantiates,
configures, and otherwise assembles a prototype object, and hands it
to the client, with no further recor...

Incontrast to the other scopes, Spring does not manage the completelifecycle of a prototype bean: the container instantiates,configures, and otherwise assembles a prototype object, and hands itto the client, with no further record of that prototype instance.Thus, although initialization lifecycle callback methods are calledon all objects regardless of scope, in the case of prototypes,configured destruction lifecycle callbacks are not called. The clientcode must clean up prototype-scoped objects and release expensiveresources that the prototype bean(s) are holding. To get the Springcontainer to release resources held by prototype-scoped beans, tryusing a custom bean post-processor, which holds a reference to beansthat need to be cleaned up.


Thenon-singleton, prototype scope of bean deployment results in thecreation of a new bean instance every time a request for thatspecific bean is made. That is, the bean is injected into anotherbean or you request it through a getBean() method call on thecontainer. As a rule, use the prototype scope for all stateful beansand the singleton scope for stateless beans.


Insome respects, the Spring container’s role in regard to aprototype-scoped bean is a replacement for the Java new operator. Alllifecycle management past that point must be handled by the client.


What is transaction Isolation?

Thedegree to which this transaction is isolated from the work of othertransactions. For example, can this transaction see uncommittedwrites from other transactions?


In other words it is about how much a transaction may be impacted by the activities ofother concurrent transactions. It a supports consistency leaving thedata across many tables in a consistent state. It involves lockingrows and/or tables in a database

What taransaction isolation levels do you know?

DEFAULT Use the default isolation level of the underlying datastore.


READ_COMMITTED A constant indicating that dirty reads are prevented; non-repeatable reads and phantom reads can occur.


READ_UNCOMMITTED A constant indicating that dirty reads, non-repeatable reads and phantom reads can occur.


REPEATABLE_READ A constant indicating that dirty reads and non-repeatable reads are prevented; phantom reads can occur.


SERIALIZABLEA constant indicating that dirty reads, non-repeatable reads andphantom reads are prevented.


What kind of problems proper transaction isolation can prevent?

Theproblem with multiple transaction


Dirty Reads A dirty read occurs when a transaction reads data that has not yet been committed. For example, suppose transaction 1 updates a row. Transaction 2 reads the updated row before transaction 1 commits the update. If transaction 1 rolls back the change, transaction 2 will have read data that is considered never to have existed.




Nonrepeatable Reads A nonrepeatable read occurs when a transaction reads the same row twice but gets different data each time. For example, suppose transaction 1 reads a row. Transaction 2 updates or deletes that row and commits the update or delete. If transaction 1 rereads the row, it retrieves different row values or discovers that the row has been deleted.




Phantoms A phantom is a row that matches the search criteria but is not initially seen. For example, suppose transaction 1 reads a set of rows that satisfy some search criteria. Transaction 2 generates a new row (through either an update or an insert) that matches the search criteria for transaction 1. If transaction 1 reexecutes the statement that reads the rows, it gets a different set of rows.


What's the difference between nonrepeatable reads and phantom reads?

1. User A runs the same query twice.




2. In between, User B runs a transaction and commits.




3. Non-repeatable read: The A row that user A has queried has a different value the second time.




4. Phantom read: All the rows in the query have the same value before and after, but different rows are being selected (because B has deleted or inserted some). Example: select sum(x) from table; will return a different result even if none of the affected rows themselves have been updated, if rows have been added or deleted.


What is transaction propagation?

Typically,all code executed within a transaction scope will run in thattransaction. However, you have the option of specifying the behaviorin the event that a transactional method is executed when atransaction context already exists. For example, code can continuerunning in the existing transaction (the common case); or theexisting transaction can be suspended and a new transaction created. Spring offers all of the transaction propagation options familiarfrom EJB CMT.


What transaction propagation levels do you know?

MANDATORY Support a current transaction, throw an exception if none exists.




NESTED Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.




NEVER Execute non-transactionally, throw an exception if a transaction exists.




NOT_SUPPORTED Execute non-transactionally, suspend the current transaction if one exists. NOTE: Actual transaction suspension will not work out-of-the-box on all transaction managers. This in particular applies to JtaTransactionManager, which requires the javax.transaction.TransactionManager to be made available it to it (which is server-specific in standard Java EE).




REQUIRED Support a current transaction, create a new one if none exists.




REQUIRES_NEW Create a new transaction, and suspend the current transaction if one exists.




SUPPORTS Support a current transaction, execute non-transactionally if none exists.


What is transaction Timeout?

Howlong this transaction runs before timing out and being rolled backautomatically by the underlying transaction infrastructure.


What is transaction Read-only status?


Aread-only transaction can be used when your code reads but does notmodify data. Read-only transactions can be a useful optimization insome cases, such as when you are using Hibernate.

Are there are any issues with transaction read-only status?

It works only for JDBC and not works almost for all JPA databases. Best practice is to use @Transactional(readOnly = true,


propagation=Propagation.SUPPORTS)


construction for not to start new transaction while reading fron DB.

What are default values for transaction parameters?

name = no defalult (required)




isolation = DEFAULT




propagation = REQUIRED




timeout = -1




read-only = false




rollback-for = no default (by default transaction rolls back only on unchecked exceptions)


@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)




no-rollback-for = no default




Name some of the design patterns used in Spring Framework?

Spring Framework is using a lot of design patterns, some of the common ones are:


1.Singleton Pattern: Creating beans with default scope.


2.Factory Pattern: Bean Factory classes


3.Prototype Pattern: Bean scopes


4.Adapter Pattern: Spring Web and Spring MVC


5.Proxy Pattern: Spring Aspect Oriented Programming support


6.Template Method Pattern: JdbcTemplate, HibernateTemplate etc


7.Front Controller: Spring MVC DispatcherServlet


8.Data Access Object: Spring DAO support


9.Dependency Injection and Aspect Oriented Programming

What is Spring MVC Interceptor and how to use it?

Spring MVC Interceptors are like Servlet Filters and allow us to intercept client request and process it.


We can intercept client request at three places – preHandle, postHandle and afterCompletion.We can create spring interceptor by implementing HandlerInterceptor interface or by extending abstract class HandlerInterceptorAdapter.


We need to configure interceptors in the spring bean configuration file. We can define an interceptor to intercept all the client requests or we can configure it for specific URI mapping too

How would you relate Spring MVC Framework to MVC architecture?

As the name suggests Spring MVC is built on top of Model-View-Controller architecture.




DispatcherServlet is the Front Controller in the Spring MVC application that takes care of all the incoming requests and delegate it to different controller handler methods.




Model can be any Java Bean in the Spring Framework, just like any other MVC framework Spring provides automatic binding of form data to java beans. We can set model beans as attributes to be used in the view pages.




View Pages can be JSP, static HTMLs etc. and view resolvers are responsible for finding the correct view page. Once the view page is identified, control is given back to the DispatcherServlet controller. DispatcherServlet is responsible for rendering the view and returning the final response to the client.