0% found this document useful (0 votes)
172 views

A.Spring Overview: Beanfactory

Spring is an open source framework for building Java applications. It provides features like inversion of control, aspect-oriented programming, and transaction management. The core Spring modules include the core container, data access/integration, web, AOP, and testing. Common implementations of the ApplicationContext include the FileSystemXmlApplicationContext which loads configuration from XML files and the ClassPathXmlApplicationContext which loads from the classpath. Spring configuration can come from multiple XML files specified in web.xml or imported from another file. The Spring MVC framework provides web development features built on the Spring core.

Uploaded by

Ashihs
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
172 views

A.Spring Overview: Beanfactory

Spring is an open source framework for building Java applications. It provides features like inversion of control, aspect-oriented programming, and transaction management. The core Spring modules include the core container, data access/integration, web, AOP, and testing. Common implementations of the ApplicationContext include the FileSystemXmlApplicationContext which loads configuration from XML files and the ClassPathXmlApplicationContext which loads from the classpath. Spring configuration can come from multiple XML files specified in web.xml or imported from another file. The Spring MVC framework provides web development features built on the Spring core.

Uploaded by

Ashihs
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

A.Spring overview 4.

Explain the Core Container (Application context)


1. What is Spring? module
Spring is an open source development framework This is the basic Spring module, which provides the
for Enterprise Java. The core features of the Spring fundamental functionality of the Spring
Framework can be used in developing any Java application, framework. BeanFactory is the heart of any spring-based
but there are extensions for building web applications on top
of the Java EE platform. Spring framework targets to make application. Spring framework was built on the top of this
Java EE development easier to use and promote good module, which makes the Spring container.
programming practice by enabling a POJO-based 5. BeanFactory implementation example
programming model. A BeanFactory is an implementation of the factory pattern that
2. What are benefits of Spring Framework? applies Inversion of Control to separate the application’s
Lightweight: Spring is lightweight when it comes to size and configuration and dependencies from the actual application
transparency. The basic version of spring framework is around code.
2MB. The most commonly used BeanFactory implementation is
Inversion of control (IOC): Loose coupling is achieved in the XmlBeanFactory class.
Spring, with the Inversion of Control technique. The objects
give their dependencies instead of creating or looking for 6. XMLBeanFactory
dependent objects. The most useful one
Aspect oriented (AOP): Spring supports Aspect oriented is org.springframework.beans.factory.xml.XmlBeanFactory , which loads its
programming and separates application business logic from beans based on the definitions contained in an XML file. This
system services. container reads the configuration metadata from an XML file
Container: Spring contains and manages the life cycle and and uses it to create a fully configured system or application.
configuration of application objects. 7. Explain the AOP module
MVC Framework: Spring’s web framework is a well-
The AOP module is used for developing aspects for our Spring-
designed web MVC framework, which provides a great
enabled application. Much of the support has been provided
alternative to web frameworks.
by the AOP Alliance in order to ensure the interoperability
Transaction Management: Spring provides a consistent
between Spring and other AOP frameworks. This module also
transaction management interface that can scale down to a
introduces metadata programming to Spring.
local transaction and scale up to global transactions (JTA).
Exception Handling: Spring provides a convenient API to 8. Explain the JDBC abstraction and DAO module
translate technology-specific exceptions (thrown by JDBC, With the JDBC abstraction and DAO module we can be sure
Hibernate, or JDO) into consistent, unchecked exceptions. that we keep up the database code clean and simple, and
3. Which are the Spring framework modules? prevent problems that result from a failure to close database
resources. It provides a layer of meaningful exceptions on top
There are around 20 modules which are generalized into Core
of the error messages given by several database servers. It
Container, Data Access/Integration, Web, AOP (Aspect
also makes use of Spring’s AOP module to provide transaction
Oriented Programming), Instrumentation and Test. The basic
management services for objects in a Spring application.
modules of the Spring framework are :
Spring Core Container 9. Explain the object/relational mapping
This layer is basically the core of Spring Framework. It
contains the following modules:
integration module
Spring also supports for using of an object/relational mapping
Core module
(ORM) tool over straight JDBC by providing the ORM module.
Bean module
Spring provides support to tie into several popular ORM
Context module
frameworks, including Hibernate, JDO, and iBATIS SQL Maps.
Expression Language module
Spring’s transaction management supports each of these ORM
Data Access/Integration
frameworks as well as JDBC.
This layer provides support to interact with the database. It
contains the following modules: 10. Explain the web module
JDBC module The Spring web module is built on the application context
Object-Relational Mapping (ORM) module module, providing a context that is appropriate for web-based
Java Messaging Service (JMS) module applications. This module also contains support for several
Object XML Mappers (OXM) module web-oriented tasks such as transparently handling multipart
Transaction Management module requests for file uploads and programmatic binding of request
Web parameters to your business objects. It also contains
This layer provides support to create web application. It integration support with Jakarta Struts.
contains the following modules:
Web module
11. Explain the Spring MVC module
Web-MVC module MVC framework is provided by Spring for building web
Web-Socket module applications. Spring can easily be integrated with other MVC
Web-Portlet module frameworks, but Spring’s MVC framework is a better choice,
Aspect Oriented Programming (AOP) since it uses IoC to provide for a clean separation of controller
In this layer you can use Advices, Pointcuts etc., to decouple logic from business objects. With Spring MVC you can
the code. declaratively bind request parameters to your business
Instrumentation – This layer provides support to class objects.
instrumentation and classloader implementations. 12. Spring configuration file
Test Spring configuration file is an XML file. This file contains the
This layer provides support to testing with JUnit and TestNG. classes information and describes how these classes are
Messaging configured and introduced to each other.
This module provides support for STOMP. It also supports an
annotation programming model that is used for routing and
13. How can we have multiple Spring
processing STOMP messages from WebSocket clients. configuration files?
Aspects web.xml contextConfigLocation: you can load them all into
This module provides support to integration with AspectJ. your Web application context via the ContextConfigLocation
element. You’re already going to have your primary Any Spring @RestController in a Spring Boot application
applicationContext here, assuming you’re writing a web should render JSON response by default as long as Jackson2 is
application. All you need to do is put some white space on the classpath.
between the declaration of the next context. 19. Spring vs Spring MVC vs Spring Boot?
applicationContext.xml import resource: you can add your
Spring: the most important feature of Spring is Dependency
primary applicationContext.xml to the web.xml and then use
Injection or Inversion of Control.
import statements in that primary context.
Spring MVC: is a complete HTTP oriented MVC framework
14. What are the common implementations of the managed by the Spring Framework and based in Servlets. It
ApplicationContext? would be equivalent to JSF in the JavaEE stack.
Spring Boot: is a utility for setting up applications quickly,
The FileSystemXmlApplicationContext container loads the
offering an out of the box configuration in order to build
definitions of the beans from an XML file. The full path of the
Spring powered applications.
XML bean configuration file must be provided to the
constructor. 20. What does a Spring application look like?
The ClassPathXmlApplicationContext container also loads the Interface: An interface that defines the functions.
definitions of the beans from an XML file. Here, you need to Bean class: It contains properties, its setter and getter
set CLASSPATH properly because this container will look bean methods, functions etc.
configuration XML file in CLASSPATH . Spring AOP: Provides the functionality of cross-cutting
concerns.
The WebXmlApplicationContext: container loads the XML file
The configuration XML file: Contains the information of
with definitions of all beans from within a web application.
classes and how to configure them.
15. What is the difference between Bean Factory The Client program: uses the function.
and ApplicationContext? B.Dependency Injection
Application contexts provide a means for resolving text 21. What is Spring IoC container?
messages, a generic way to load file resources (such as The Spring IoC is responsible for creating the
images), they can publish events to beans that are registered objects,managing them with dependency injection (DI),
as listeners. In addition, operations on the container or beans wiring them together, configuring them, as also managing
in the container, which have to be handled in a programmatic their complete lifecycle.
fashion with a bean factory, can be handled declaratively in an
application context. The application context
22. What are the benefits of IOC?
implements MessageSource , an interface used to obtain localized IOC or dependency injection minimizes the amount of code in
an application.
messages, with the actual implementation being pluggable.
It makes easy to test applications, since no singletons or JNDI
16. What are some of the best practices for Spring lookup mechanisms are required in unit tests.
Loose coupling is promoted with minimal effort and least
Framework? intrusive mechanism.
Some of the best practices for Spring Framework are:
IOC containers support eager instantiation and lazy loading of
Define singleton beans with names same as their class or
services.
interface names
Place Spring bean configuration files under a folder instead of 23. How many types of IOC containers are there in
root folder spring?
Give common prefixes or suffixes to Spring bean configuration
BeanFactory: A BeanFactory is essentially nothing more than
files
the interface for an advanced factory capable of maintaining a
Avoid using import elements within Spring XML configuration
registry of different beans and their dependencies. The
files as much as possible
BeanFactory enables you to read bean definitions and access
Stay away from auto wiring in XML based bean configurations
them using the bean factory.
Always externalize bean property values with property
ApplicationContext: The ApplicationContext is the central
placeholders
interface within a Spring application for providing
Select default version-less XSD when importing namespace
configuration information to the application. It is read-only at
definitions
run time, but can be reloaded if necessary and supported by
Always place classpath prefix in resource paths
the application. A number of classes implement the
Create a setter method even though you use field level auto
ApplicationContext interface, allowing for a variety of
wiring
configuration options and types of applications.
Create a separate service layer even though service methods
barely delegate their responsibilities to corresponding DAO 24. BeanFactory vs ApplicationContext
methods Application Context:
17. What are the various ways of using Spring Bean instantiation/wiring
Automatic BeanPostProcessor registration
Framework? Automatic BeanFactoryPostProcessor registration
You can use Spring Framework: Convenient MessageSource access (for i18n)
for writing web applications ApplicationEvent publication
for exposing RESTful services BeanFactor:
to secure your web applications Bean instantiation/wiring
for communicating with databases 25. What is Dependency Injection in Spring?
for handling long running jobs
Dependency Injection, an aspect of Inversion of Control (IoC),
to handle external resources or systems you have to work
is a general concept, and it can be expressed in many different
with
ways.This concept says that you do not create your objects
for testing purposes
but describe how they should be created. You don’t directly
for standalone java projects
connect your components and services together in code but
to convert your application into an executable
describe which services are needed by which components in a
to integrate Social Media into your applications
configuration file. A container (the IOC container) is then
18. How can we use Spring to create Restful Web responsible for hooking it all up.
Service returning JSON response?
26. What is the difference between Tight Coupling In session scope, a bean definition is scoped to an HTTP
session. This scope is also valid only in a web-aware Spring
and Loose Coupling? ApplicationContext.
Tight Coupling: In global-session scope, a bean definition is scoped to a global
Tight coupling is when a group of classes are highly HTTP session. This is also a case used in a web-aware Spring
dependent on one another. ApplicationContext.
Loose Coupling: The default scope of a Spring Bean is Singleton .
Loose coupling is achieved by means of a design that
promotes single-responsibility and separation of concerns.
34. Are Singleton beans thread safe in Spring
27. What are the different types of IoC Framework?
No, singleton beans are not thread-safe in Spring framework.
(dependency injection)?
Constructor-based dependency injection: Constructor-based
35. Explain Bean lifecycle in Spring framework
DI is accomplished when the container invokes a class The spring container finds the bean’s definition from the XML
constructor with a number of arguments, each representing a file and instantiates the bean.
dependency on other class. Spring populates all of the properties as specified in the bean
Setter-based dependency injection: Setter-based DI is definition (DI).
accomplished by the container calling setter methods on your If the bean implements BeanNameAware interface, spring passes
beans after invoking a no-argument constructor or no- the bean’s id to setBeanName() method.
argument static factory method to instantiate your bean. If Bean implements BeanFactoryAware interface, spring passes
28. Which DI would you suggest Constructor- the beanfactory to setBeanFactory() method.
based or setter-based DI? If there are any bean BeanPostProcessors associated with the
You can use both Constructor-based and Setter-based bean, Spring calls postProcesserBeforeInitialization() method.
Dependency Injection. The best solution is using constructor If the bean implements IntializingBean ,
arguments for mandatory dependencies and setters for its afterPropertySet() method is called. If the bean has init
optional dependencies.
method declaration, the specified initialization method is
C.Spring Beans called.
29. What are Spring beans? If there are any BeanPostProcessors associated with the bean,
The Spring Beans are Java Objects that form the backbone of their postProcessAfterInitialization() methods will be called.
a Spring application. They are instantiated, assembled, and If the bean implements DisposableBean , it will call
managed by the Spring IoC container. These beans are the destroy() method.
created with the configuration metadata that is supplied to
the container, for example, in the form of 36. Which are the important beans lifecycle
XML <bean/> definitions. methods? Can you override them?
Beans defined in spring framework are singleton beans. There There are two important bean lifecycle methods. The first one
is an attribute in bean tag named "singleton" if specified true is setup which is called when the bean is loaded in to the
then bean becomes singleton and if set to false then the bean container. The second method is the teardown method which is
becomes a prototype bean. By default it is set to true. So, all called when the bean is unloaded from the container.
the beans in spring framework are by default singleton beans. The bean tag has two important attributes ( init-
30. What does a Spring Bean definition contain? method and destroy-method ) with which you can define your own
A Spring Bean definition contains all configuration metadata custom initialization and destroy methods. There are also the
which is needed for the container to know how to create a correspondive annotations( @PostConstruct and @PreDestroy ).
bean, its lifecycle details and its dependencies.
31. How do you provide configuration metadata to 37. What are inner beans in Spring?
When a bean is only used as a property of another bean it can
the Spring Container? be declared as an inner bean. Spring’s XML-based
There are three important methods to provide configuration configuration metadata provides the use of <bean/> element
metadata to the Spring Container: inside the <property/> or <constructor-arg/> elements of a bean
XML based configuration file. definition, in order to define the so-called inner bean. Inner
Annotation-based configuration beans are always anonymous and they are always scoped as
Java-based configuration prototypes.
32. How do you define the scope of a bean? 38. How can you inject a Java Collection in Spring?
When defining a <bean> in Spring, we can also declare a scope Spring offers the following types of collection configuration
for the bean. It can be defined through the scope attribute in elements:
the bean definition. For example, when Spring has to produce The <list> type is used for injecting a list of values, in the
a new bean instance each time one is needed, the case that duplicates are allowed.
bean’s scope attribute to be prototype . On the other hand, The <set> type is used for wiring a set of values but without
when the same instance of a bean must be returned by Spring any duplicates.
every time it is needed, the the bean scope attribute must be The <map> type is used to inject a collection of name-value
set to singleton . pairs where name and value can be of any type.
The <props> type can be used to inject a collection of name-
33. Explain the bean scopes supported by Spring
There are five scoped provided by the Spring Framework value pairs where the name and value are both Strings.
supports following five scopes: 39. What is bean wiring?
In singleton scope, Spring scopes the bean definition to a Wiring, or else bean wiring is the case when beans are
single instance per Spring IoC container. combined together within the Spring container. When wiring
In prototype scope, a single bean definition has any number beans, the Spring container needs to know what beans are
of object instances. needed and how the container should use dependency
In request scope, a bean is defined to an HTTP request. This injection to tie them together.
scope is valid only in a web-aware Spring ApplicationContext.
40. What is bean autowiring?
The Spring container is able to autowire @ResponseBody – for sending Object as response, usually for
relationships between collaborating beans. This means that it sending XML or JSON data as response.
is possible to automatically let Spring resolve collaborators @PathVariable – for mapping dynamic values from the URI to
(other beans) for a bean by inspecting the contents of handler method arguments.
the BeanFactory without using <constructor- @Autowired – provides more fine-grained control over where
arg> and <property> elements. and how autowiring should be accomplished. It can be used to
autowire bean on the setter method just like @Required
41. Explain different modes of autowiring? annotation, on the constructor, on a property or pn methods
The autowiring functionality has five modes which can be with arbitrary names and/or multiple arguments.
used to instruct Spring container to use autowiring for @Qualifier – When there are more than one beans of the same
dependency injection: type and only one is needed to be wired with a property, the
no: This is default setting. Explicit bean reference should be @Qualifier annotation is used along with @Autowired
used for wiring. annotation to remove the confusion by specifying which exact
byName: When autowiring byName , the Spring container looks bean will be wired.
at the properties of the beans on which autowire attribute is set @Scope – for configuring scope of the spring bean.
to byName in the XML configuration file. It then tries to match @Configuration – indicates that the class can be used by the
Spring IoC container as a source of bean definitions.
and wire its properties with the beans defined by the same @ComponentScan – all the classes available under a package
names in the configuration file. will be scanned when this annotation is applied.
byType: When autowiring by datatype , the Spring container @Bean – for java based configurations, tells spring that a
looks at the properties of the beans on which autowire attribute method annotated with @Bean will return an object that
is set to byType in the XML configuration file. It then tries to should be registered as a bean in the spring application
match and wire a property if its type matches with exactly one context.
of the beans name in configuration file. If more than one such AspectJ annotations for configuring aspects and advices,
beans exist, a fatal exception is thrown. @Aspect, @Before, @After, @Around, @Pointcut etc.
constructor: This mode is similar to byType , but type applies to 45. What does the @RequestParam annotation
constructor arguments. If there is not exactly one bean of the do?
constructor argument type in the container, a fatal error is
The @RequestParam annotation in spring binds the parameter
raised.
values of a query string to the method argument of a
autodetect: Spring first tries to wire using autowire by
controller.
constructor, if it does not work, Spring tries to autowire
46. What is the importance of the annotation @Primary
by byType .
When there are multiple beans of the same data-type,
42. Are there limitations with autowiring? developers use the Spring-specific @Primary annotation that
Limitations of autowiring are: automatically gives the higher preference to a particular bean.
Overriding: You can still specify dependencies This annotation can be used on any class directly or indirectly
using <constructor-arg> and <property> settings which will always annotated with the @Component annotation or on methods
annotated with the @Bean annotation.
override autowiring.
Primitive data types: You cannot autowire simple properties 47. What is the difference between the
such as primitives, Strings, and Classes.
Confusing nature: Autowiring is less exact than explicit
Configuration types XML and Annotation?
Advantages of the annotation:
wiring, so if possible prefer using explicit wiring.
All the information is in a single file
43. Can you inject null and empty string values in When the class changes, no need to modify the xml file
Spring? Advantages of XML file:
Clear separation between the POJO and its behavior
Yes, you can.
When you do not know which POJO is responsible for the
behavior, it is easier to find that POJO
D.Spring Annotations 48. What is the role of @SpringBootApplication?
44. What are some of the important Spring The @SpringBootApplication annotation was introduced in
annotations? Spring Boot 1.2.0 and it enables the auto-
configurationfeature.
Some of the Spring annotations that I have used in my project
This annotation encapsulates the working of three different
are:
annotations:
@Component is used to indicate that a class is a component.
@Configuration: Allows the developers to explicitly register
These classes are used for auto-detection and configured as
the beans
bean when annotation based configurations are used.
@ComponentScan: Enables the component-scanning so that
@Controller is a specific type of component, used in MVC
the controller class and other components will be
applications and mostly used with @RequestMapping
automatically discovered and registered as beans in spring’s
annotation.
application context
@Repository annotation is used to indicate that a component
@EnableAutoConfiguration: Enables the auto-configuration
is used as repository and a mechanism to
feature of spring boot
store/retrieve/search data. We can apply this annotation with
This annotation takes up the following optional parameters:
DAO pattern implementation classes.
exclude : Excludes the list of classes from the auto-
@Service is used to indicate that a class is a Service. Usually,
the business facade classes that provide some services are configuration
excludeNames : Excludes the list of fully qualified class names
annotated with this.
@Required – This annotation simply indicates that the from the auto configuration
affected bean property must be populated at configuration scanBasePackage : Provides the list of packages which must be

time, through an explicit property value in a bean definition or applied for scanning
through autowiring. The container throws scanBasePackageClasses : Provides the list of classes in the other
BeanInitializationException if the affected bean property has package which must be applied for scanning
not been populated.
49. Explain the @InitBinder?
This annotation is decorated on a method in which a date NamedParameterJdbcTemplate
format is declared, and throughout the class, the defined date SimpleJdbcInsert
format is used. Whenever the binding happens with a date SimpleJdbcCall
field @InitBinder; annotation says to use the 58. How can JDBC be used more efficiently in the
CustomDateEditor, which in return uses the date format
mentioned in @InitBinder. Spring framework?
50. Define @ControllerAdvice? When using the Spring JDBC framework the burden of
resource management and error handling is reduced. So
Classes with @ControllerAdvice can be declared explicitly as
developers only need to write the statements and queries to
Spring beans or auto-detected via classpath scanning. All such
get the data to and from the database. JDBC can be used more
beans are sorted via AnnotationAwareOrderComparator, i.e.
efficiently with the help of a template class provided by Spring
based on @Order and Ordered, and applied in that order at
framework, which is the JdbcTemplate (example here).
runtime. For handling exceptions, an @ExceptionHandler will
be picked on the first advice with a matching exception 59. JdbcTemplate
handler method. For model attributes and InitBinder JdbcTemplate class provides many convenience methods for
initialization, @ModelAttribute and @InitBinder methods will
doing things such as converting database data into primitives
also follow @ControllerAdvice order.
or objects, executing prepared and callable statements, and
51. Can we send an Object as the response of providing custom database error handling.
Controller handler method? 60. How can you fetch records by spring
Yes we can send JSON or XML based response in restful web JdbcTemplate?
services, using the @ResponseBody annotation.
There are two interfaces that can be used to fetch records
52. Explain @ModelAttribute? from the database:
The @ModelAttribute annotation refers to the property of the ResultSetExtractor
Model object and is used to prepare the model data. This RowMapper
annotation binds a method variable or the model object to a 61. What is the advantage of
named model attribute. The annotation accepts an optional
value which indicates the name of the model attribute. The NamedParameterJdbcTemplate?
@ModelAttribute annotation can be used at the parameter NamedParameterJdbcTemplate is built upon JDBCTemplate
level or the method level. The use of this annotation at the which is provided by spring and used for lower level
parameter level is to accept the request form values while at communication with databases. It makes possible to pass SQL
the method level is to assign the default values to a model. Let query arguments as key value pairs. As a result the program
me explain you further with the help of some examples. code is much more readable and therefore serves as better
53. @RequestMapping annotation documentation compared to the indexed or the “?”
placeholder approach. The latter is harder to follow specially if
The @RequestMapping annotation is used to map the web
the number of parameters is huge.
request onto a handler class (i.e. Controller) or a handler
method and it can be used at the Method Level or the Class 62. What is Spring JDBCTemplate class and how to
Level. If developers use the @RequestMapping annotation at use it?
a class level, it will be as a relative path for the method level
The JdbcTemplate class executes SQL queries, update
path.
statements and stored procedure calls, performs iteration
54. What is Spring Java-Based Configuration? Give over ResultSets and extraction of returned parameter values.
some annotation example. It handles the creation and release of resources, thus avoiding
errors such as forgetting to close the connection. It also
Java based configuration option enables you to write most of
catches JDBC exceptions and translates them to the generic,
your Spring configuration without XML but with the help of
more informative, exception hierarchy defined in the
few Java-based annotations.
org.springframework.dao package.
An example is the @Configuration annotation, that indicates that
the class can be used by the Spring IoC container as a source 63. What is the difference between JDBC and
of bean definitions. Another example is the @Bean annotated Spring JDBC?
method that will return an object that should be registered as Spring JDBC value-add provided by the Spring Framework’s
a bean in the Spring application context. on top JDBC layer
55. What is Annotation-based container Define connection parameters
Open the connection
configuration? Specify the statement
An alternative to XML setups is provided by annotation-based Prepare and execute the statement
configuration which relies on the bytecode metadata for Set up the loop to iterate through the results (if any)
wiring up components instead of angle-bracket declarations. Do the work for each iteration
Instead of using XML to describe a bean wiring, the developer Process any exception
moves the configuration into the component class itself by Handle transactions
using annotations on the relevant class, method, or field Close the connection
declaration. 64. Spring DAO support
56. How do you turn on annotation wiring? The Data Access Object (DAO) support in Spring is aimed at
Annotation wiring is not turned on in the Spring container by making it easy to work with data access technologies like
default. In order to use annotation based wiring we must JDBC, Hibernate or JDO in a consistent way. This allows us to
enable it in our Spring configuration file by switch between the persistence technologies fairly easily and
configuring <context:annotation-config/> element. to code without worrying about catching exceptions that are
E.Spring Data Access specific to each technology.

57. Which classes are present in spring JDBC API? 65. What are the ways to access Hibernate by
Spring framework provides the following approaches for Jdbc using Spring?
database access: There are two ways to access Hibernate with Spring:
JdbcTemplate Inversion of Control with a Hibernate Template and Callback.
SimpleJdbcTemplate
Extending HibernateDAOSupport and Applying an AOP Interceptor Aspects can be configured as normal spring beans.
node. d. As any other AOP framework, it weaves cross cutting
concerns into the classes, without making a call to the cross
66. ORM’s Spring support cutting concerns from those classes.
Spring supports the following ORM’s: e. Centralize or modularize the cross cutting concerns
Hibernate Easy to maintain and make changes to the aspects
iBatis Changes need to be made in one place.
JPA (Java Persistence API) In one of your classes you don’t want to have logging, it can
TopLink easily be achieved by modifying the point cut in the respective
JDO (Java Data Objects) aspect (logging aspect). So you need to make changes in only
OJB one place.
67. How can we integrate Spring and Hibernate f. Provision to create aspects using schema based (XML
configuration) or @AspectJ annotation based style.
using HibernateDaoSupport? g. Easy to configure
Use Spring’s SessionFactory called LocalSessionFactory . The
73. What are the AOP implementation?
integration process is of 3 steps:
AOP implementations:
Configure the Hibernate SessionFactory
Spring AOP:
Extend a DAO Implementation from HibernateDaoSupport
Runtime weaving through proxy is done
Wire in Transaction Support with AOP It supports only method level PointCut
68. Types of the transaction management Spring It is DTD based
Apache AspectJ
support Compile time weaving through AspectJ Java tools is done
Spring supports two types of transaction management: It suports field level Pointcuts
Programmatic transaction management: This means that you It is schema based and Annotation configuration
have managed the transaction with the help of programming. JBoss AOP
That gives you extreme flexibility, but it is difficult to JBoss AOP is not only a framework, but also a prepackaged
maintain. set of aspects that are applied via annotations, pointcut
Declarative transaction management: This means you expressions, or dynamically at runtime. Some of these include
separate transaction management from the business code. caching, asynchronous communication, transactions, security,
You only use annotations or XML based configuration to remoting, and many many more.
manage the transactions.
74. What are the AOP terminology?
69. What are the benefits of the Spring Aspect
Framework’s transaction management? Advice
It provides a consistent programming model across different Pointcut
transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO. JoinPoint
It provides a simpler API for programmatic transaction Introduction
management than a number of complex transaction APIs such Target Object
as JTA. AOP Proxy
It supports declarative transaction management. Weaving
It integrates very well with Spring’s various data access 75. Aspect
abstractions. The core construct of AOP is the aspect, which encapsulates
70. Which Transaction management type is more behaviors affecting multiple classes into reusable modules. It
ia a module which has a set of APIs providing cross-cutting
preferable? requirements. For example, a logging module would be called
Most users of the Spring Framework choose declarative AOP aspect for logging. An application can have any number
transaction management because it is the option with the of aspects depending on the requirement. In Spring AOP,
least impact on application code, and hence is most consistent aspects are implemented using regular classes annotated with
with the ideals of a non-invasive lightweight container. the @Aspect annotation ( @AspectJ style).
Declarative transaction management is preferable over
programmatic transaction management though it is less 76. Join point
flexible than programmatic transaction management, which The join point represents a point in an application where we
allows you to control transactions through your code. can plug-in an AOP aspect. It is the actual place in the
application where an action will be taken using Spring AOP
framework.
F.Spring Aspect Oriented Programming (AOP)
71. Explain AOP 77. Advice
The advice is the actual action that will be taken either before
Aspect-oriented programming, or AOP, is a programming
or after the method execution. This is actual piece of code that
technique that allows programmers to modularize
is invoked during the program execution by the Spring AOP
crosscutting concerns, or behavior that cuts across the typical
framework.
divisions of responsibility, such as logging and transaction
Spring aspects can work with five kinds of advice:
management.
before: Run advice before the a method execution.
72. What are the advantages of spring AOP? after: Run advice after the a method execution regardless of
a. It is non-invasive its outcome.
Your service/domain classes get advised by the aspects (cross after-returning: Run advice after the a method execution only
cutting concerns) without adding any Spring AOP related if method completes successfully.
classes or interfaces into the service/domain classes. after-throwing: Run advice after the a method execution only
Allows the developer to concentrate on the business code, if method exits by throwing an exception.
instead the cross cutting concerns. around: Run advice before and after the advised method is
b. Its implemented in pure Java invoked.
No need for a special compilation unit, or a special class 78. Pointcut
loader
c. It uses Spring’s IOC for dependency injection
The pointcut is a set of one or more joinpoints where an 89. List out all the concepts that are available in
advice should be executed. You can specify pointcuts using
expressions or patterns. the MVC Architecture?
79. What is Introduction? The browser sends a request to DispatcherServlet
DispatcherServlet knows the HanderMapping and can find the
An Introduction allows us to add new methods or attributes to
appropriate controllers
existing classes.
Controllers execute the request and put the data in the model
80. What is Target object? and return back the view name to the DispatcherServlet.
The target object is an object being advised by one or more DispatcherServlet uses the view name and ViewResolver to
aspects. It will always be a proxy object. It is also referred to map to the view.
as the advised object. 90. DispatcherServlet
81. What is a Proxy? The Spring Web MVC framework is designed around
A proxy is an object that is created after applying advice to a a DispatcherServlet that handles all the HTTP requests and
target object. When you think of client objects the target responses.
object and the proxy object are the same.
91. WebApplicationContext
82. What are the different types of AutoProxying? The WebApplicationContext is an extension of the
BeanNameAutoProxyCreator
plain ApplicationContext that has some extra features necessary
DefaultAdvisorAutoProxyCreator
Metadata autoproxying for web applications. It differs from a
normal ApplicationContext in that it is capable of resolving
83. What is Weaving? What are the different themes, and that it knows which servlet it is associated with.
points where weaving can be applied? 92. What is Controller in Spring MVC framework?
Weaving is the process of linking aspects with other Controllers provide access to the application behavior that you
application types or objects to create an advised object. typically define through a service interface. Controllers
Weaving can be done at compile time, at load time, or at interpret user input and transform it into a model that is
runtime. represented to the user by the view. Spring implements a
84. What is the difference between concern and controller in a very abstract way, which enables you to create
a wide variety of controllers.
cross-cutting concern in Spring AOP
The Concern is behavior we want to have in a module of an 93. How would you relate Spring MVC Framework
application. A Concern may be defined as a functionality we to MVC architecture?
want to implement. Spring MVC framework:
The cross-cutting concern is a concern which is applicable The Spring Framework is an open source application
throughout the application and it affects the entire framework and inversion of control container for the Java
application. For example, logging, security and data transfer platform.
are the concerns which are needed in almost every module of MVC architecture:
an application, hence they are cross-cutting concerns. Model View Controller (MVC) as it is popularly called, is a
85. Explain XML Schema-based aspect software design pattern for developing web applications
implementation? 94. What is ViewResolver in Spring MVC?
In this implementation case, aspects are implemented using Spring provides ViewResolver, which enable you to render
regular classes along with XML based configuration. models in a browser without tying you to a specific view
technology. Out of the box, Spring enables you to use JSPs,
86. Explain annotation-based (@AspectJ based) Velocity templates and XSLT views, for example. The two
aspect implementation interfaces which are important to the way Spring handles
This implementation case ( @AspectJ based implementation) views are ViewResolver and View. The ViewResolver provides
refers to a style of declaring aspects as regular Java classes a mapping between view names and actual views. The View
annotated with Java 5 annotations. interface addresses the preparation of the request and hands
the request over to one of the view technologies.

G.Spring Model View Controller (MVC)


95. What is a MultipartResolver and when its
87. What is Spring MVC framework? used?
Spring MVC provide multipart support with MultipartResolver.
Spring comes with a full-featured MVC framework for building
The MultipartResolver parses inbound multipart requests. You
web applications. Although Spring can easily be integrated
can enable multipart support by registering a
with other MVC frameworks, such as Struts, Spring’s MVC
MultipartResolver bean in the DispatcherServlet application
framework uses IoC to provide a clean separation of controller
context.
logic from business objects. It also allows to declaratively
bind request parameters to business objects. 96. How to upload file in Spring MVC Application?
88. What are the minimum configurations needed Spring provides built-in support for uploading files through
MultipartResolver interface implementations. There is also a
to create Spring MVC application? validator for the field, which will be used to check if the file
For creating a simple Spring MVC application, we would need uploaded is of size greater than zero. There is finally a simple
to do the following tasks: view that contains a form with the option to upload a file.
Add spring-context and spring-webmvc dependencies in the
project.
97. How to validate form data in Spring Web MVC
Configure DispatcherServlet in the web.xml file to handle Framework?
requests through spring container. There are 3 different ways to perform validation : using
Spring bean configuration file to define beans, if using annotation, manually, or a mix of both.
annotations then it has to be configured here. Also we need to
configure view resolver for view pages.
98. What is Spring MVC Interceptor and how to
Controller class with request mappings defined to handle the use it?
client requests.
Spring’s handler mapping mechanism includes
handler interceptors, which are useful when you want to
apply specific functionality to certain requests, for example,
checking for a principal. Interceptors must
implement HandlerInterceptor from
the org.springframework.web.servlet package. This interface defines
three methods:
preHandle is called before the actual handler is executed.

postHandle is called after the handler is executed.

afterCompletion is called after the complete request has finished.

H.Authentication and authorization


99. What is Spring Security?
Spring security is one of the most important modules of the
Spring framework. It enables the developers to integrate the
security features easily and in a managed way. In the
following example, we will show how to implement Spring
Security in a Spring MVC application.
100. Why Spring Boot?
Here are some useful benefits of using Spring Boot:
Automatic configuration of an application uses intelligent
defaults based on the classpath and the application context,
but they can be overridden to suit the developer’s
requirements as needed.
When creating a Spring Boot Starter project, you select the
features that your application needs and Spring Boot will
manage the dependencies for you.
A Spring Boot application can be packaged as a JAR file. The
application can be run as a standalone Java application from
the command line using the java -jar command.
When developing a web application, Spring Boot configures an
embedded Tomcat server so that it can be run as a standalone
application. (Tomcat is the default, but you can configure
Jetty or Undertow instead.) You can package the application
as a WAR file and deploy it to an external servlet container if
you prefer
Spring Boot includes many useful non-functional features
(such as security and health checks) right out of the box.

You might also like