0% found this document useful (0 votes)
16 views15 pages

SPRING MyNote-All

The document provides an overview of key concepts in Spring Framework, including Inversion of Control (IoC), Dependency Injection (DI), and various bean scopes such as singleton and prototype. It explains how to call stored procedures, the differences between BeanFactory and ApplicationContext, and the limitations of auto-wiring. Additionally, it covers annotations like @Autowired and @RequestMapping, and the role of the DispatcherServlet as a front controller in Spring MVC.

Uploaded by

Bl Gocher
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views15 pages

SPRING MyNote-All

The document provides an overview of key concepts in Spring Framework, including Inversion of Control (IoC), Dependency Injection (DI), and various bean scopes such as singleton and prototype. It explains how to call stored procedures, the differences between BeanFactory and ApplicationContext, and the limitations of auto-wiring. Additionally, it covers annotations like @Autowired and @RequestMapping, and the role of the DispatcherServlet as a front controller in Spring MVC.

Uploaded by

Bl Gocher
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 15

Q What is IOC or Dependency Injection?

- The basic concept of IOC (Dependency of Injection) is that you do not create your
objects but describe how they should be
created.
describe which services are needed by which components in a configuration file.

Q What is Bean Factory in Spring?


- A Bean Factory that contains collections of beans. The Bean Factory holds bean
definition of multiple beans and then instantiates the bean when asked by client.

Q What are the different types of IOC?


There are three types of dependency Injection:
1. Constructor Injection :
- Dependencies are provided as a constructor parameter.
In configuration file :

<bean id="helloWorldBean" class="com.xyz.services.HelloWorld">


<constructor-arg ref="fooBean" />
</bean>
<bean id="fooBean" class="com.xyz.service.Foo">
</bean>

2. Setter Injection :
- Dependencies are assigned through setter method.
in configuration file :

<bean id="helloWorldBean" class="


com.xyz.services.HelloWorld">
<property name=fooBean ref="fooBean" />
</bean>
<bean id="fooBean" class="com.xyz.service.Foo">
</bean>

Q what are the Different Spring Bean Scope.


------------------------------
1. singleton : Return a single bean instance per Spring IOC container.
2. prototype : Return a new bean instance each time when requested.
3. request : Return a single bean instance per HTTP request.
4. session : Return a single bean instance per HTTP session.
5. global session : Return a single bean instance per global HTTP session and only
valid when used in portlet context.

Q 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.
ex:
Use StoredProcedure class of org.springframework.jdbc.object

The Code:
First Create subclass of StoredProcedure: MyStoredProcedure

class MyStoredProcedure extends StoredProcedure {

public MyStoredProcedure(JdbcTemplate jdbcTemplate, String name) {

super(jdbcTemplate, name);
setFunction(false);

}
}
Use MyStoredProcedure to call database stored procedure:

//Pass jdbcTemlate and name of the stored Procedure.


MyStoredProcedure myStoredProcedure = new MyStoredProcedure(jdbcTemplate,
"PROC_TEST");

//Sql parameter mapping


SqlParameter fNameParam = new SqlParameter("fName", Types.VARCHAR);
SqlParameter lNameParam = new SqlParameter("lName", Types.VARCHAR);
SqlOutParameter msgParam = new SqlOutParameter("msg", Types.VARCHAR);
SqlParameter[] paramArray = {fNameParam, lNameParam, msgParam};

myStoredProcedure.setParameters(paramArray);
myStoredProcedure.compile();

//Call stored procedure


Map storedProcResult = myStoredProcedure.execute("FirstNameValue", "
LastNameValue");

Q What is the difference between singleton and prototype bean?

Mainly it is the scope of a beans which defines their existence on the application
Singleton : It means single bean definition to a single object instance per Spring
IOC container.
Prototype : It means a single bean definition to any number of object instances.

Q How do beans become 'singleton' or prototype?


- There exists an attribute in bean tag, called scope='singleton�.
- If it is marked 'true', the bean becomes 'singleton'.
- If it is marked 'false', the bean becomes 'prototype'.

Q What type of transaction Management Spring support?


Spring supports two types of transaction management:
1. Programmatic transaction management
2. Declarative transaction management.

Q What is Auto Wiring in Spring?

- The Auto-wiring in spring framework can be performed by configuring in xml


and
Spring Auto-Wiring with Annotation @Autowired.

- Auto-wiring beans with xml configuration: In Spring framework, you can wire beans
automatically with auto-wiring feature. To enable auto-wiring just define the
�autowire� attribute in <bean> tag.

<bean id="customer" class="com.test.autowire.Customer" autowire="byName" />

- There are five modes of Auto-wiring supported.

1. no � Default, no auto wiring, set it manually via �ref� attribute.


<bean id="customer" class="com.test.autowire.Customer">
<property name="person" ref="person" />
</bean>
<bean id="person" class="com.test.autowire.Person" />

2. byName � Auto wiring by property name. If the name of a bean is same as the name
of other bean property, auto wire it.

- In below example the name of the person bean is same as name of �customer� bean�s
property Person object. So spring will auto-wire it via setter method.
<bean id="customer" class="com.test.autowire.Customer" autowire="byName"/>
<bean id="person" class="com.test.autowire.Person" />

3. byType � Auto wiring by property data type. If data type of a bean is compatible
with the data type of other bean property, auto wire it.

- In below example the data type of the person bean is same as name of �customer�
bean�s property Person object. So spring will auto-wire it via setter method.
<bean id="customer" class="com.test.autowire.Customer" autowire="byType"/>
<bean id="person" class="com.test.autowire.Person" />

4. constructor � byType mode in constructor argument.

- Here the data type of �person� bean is same as the constructor argument data type
in �customer� bean�s property (Person object), so, Spring auto wired it via
constructor method � �public Customer(Person person)�
<bean id="customer" class="com.test.autowire.Customer" autowire="constructor"/>
<bean id="person" class="com.test.autowire.Person" />

5. autodetect � If a default constructor is found, use �autowired by constructor�;


Otherwise, use �autowire by type�.

- If a default constructor is found, uses �constructor�; Otherwise, uses �byType�.


In this case, since there is a default constructor in �Customer� class, so, Spring
auto wired it via constructor method � �public Customer(Person person)�.
<bean id="customer" class="com.test.autowire.Customer" autowire="autodetect"/>
<bean id="person" class="com.test.autowire.Person" />

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

Q 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.
What is inner Bean Definition?

- A bean definition added inside the property or constructor-arg elements are


called inner bean.

Q List the limitations of auto wiring.

Autowiring has the following limitations :


1. Overriding and auto wiring are caused due to dependency in property and
constructor argument setting.
2. Less precise as compared to explicit wiring.
3. Tools that generate documentation using a spring might not have access to wiring
information.
4. There is a possibility of clash between bean definitions and argument or method
to be wired.
5. The problem does not occur much in case of maps, arrays and collection and
cannot be resolved randomly for dependencies which expect one value.

12. Spring configuration file


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.

13. What is Spring IoC container?


The Spring IoC is responsible for creating the objects,managing them (with
dependency injection (DI)), wiring them together, configuring them, as also
managing their complete lifecycle.

14. What are the benefits of IOC?


IOC or dependency injection minimizes the amount of code in an application. It
makes easy to test applications, since no singletons or JNDI
lookup mechanisms are required in unit tests. Loose coupling is promoted with
minimal effort and least intrusive mechanism. IOC containers
support eager instantiation and lazy loading of services.
15. What are the common implementations of the ApplicationContext?
The FileSystemXmlApplicationContext container loads the definitions of the beans
from an XML file. The full path of the XML bean
configuration file must be provided to the constructor.
The ClassPathXmlApplicationContext container also loads the definitions of the
beans from an XML file. Here, you need to set
CLASSPATH
properly because this container will look bean configuration XML file in
CLASSPATH
.
The WebXmlApplicationContext: container loads the XML file with definitions of all
beans from within a web application.

16. What is the difference between Bean Factory and ApplicationContext?


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

18. What is Dependency Injection in Spring?


Dependency Injection, an aspect of Inversion of Control (IoC), is a general
concept, and it can be expressed in many different ways.This
concept says that you do not create your objects but describe how they should be
created. You don�t directly connect your components and
services together in code but describe which services are needed by which
components in a configuration file. A container (the IOC container)
is then responsible for looking it all up.

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


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.

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


You can use both Constructor-based and Setter-based Dependency Injection. The best
solution is using constructor arguments for mandatory
dependencies and setters for optional dependencies.

25. Explain the bean scopes supported by Spring


There are five scoped provided by the Spring Framework supports following five
scopes:
In singleton scope, Spring scopes the bean definition to a single instance per
Spring IoC container.
In prototype scope, a single bean definition has any number of object instances.
In request scope, a bean is defined to an HTTP request. This scope is valid only in
a web-aware Spring ApplicationContext.
In session scope, a bean definition is scoped to an HTTP session. This scope is
also valid only in a web-aware Spring ApplicationContext.
In global-session scope, a bean definition is scoped to a global HTTP session. This
is also a case used in a web-aware Spring
ApplicationContext.
The default scope of a Spring Bean is
Singleton
.
26. Are Singleton beans thread safe in Spring Framework?
No, singleton beans are not thread-safe in Spring framework.

How can you inject a Java Collection in Spring?


Spring offers the following types of collection configuration elements:
The
<list>
type is used for injecting a list of values, in the case that duplicates are
allowed.
The
<set>
type is used for wiring a set of values but without any duplicates.
The
<map>
type is used to inject a collection of name-value pairs where name and value can be
of any type.
The
<props>
type can be used to inject a collection of name-value pairs where the name and
value are both Strings.

31. What is bean wiring?


Wiring, or else bean wiring is the case when beans are combined together within the
Spring container. When wiring beans, the Spring
container needs to know what beans are needed and how the container should use
dependency injection to tie them together.
32. 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 a bean by inspecting the contents of the
BeanFactory.
The autowiring functionality has five modes. These are
�no�, �byName�, �byType�, �constructor�, and �autodetect�.
Note:- The default mode is �no� i.e. by default autowiring is turned off in
traditional XML based configuration.
No control of programmer.
It can't be used for primitive and string values.

33. Explain different modes of 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. Explicit bean reference should be used for wiring.

byName: When autowiring byName, the Spring container looks at the properties of the
beans on which autowire attribute is set to byName
in the XML configuration file. It then tries to match and wire its properties with
the beans defined by the same names in the configuration file.

byType: When autowiring by datatype, the Spring container looks at the properties
of the beans on which autowire attribute is set to
byType in the XML configuration file. It then tries to match and wire a property if
its type matches with exactly one of the beans name in configuration file. If more
than one such beans exist, a fatal exception is thrown.

constructor: This mode is similar to byType , but type applies to constructor


arguments. If there is not exactly one bean of the constructor argument type in the
container, a fatal error is raised.

autodetect: Spring first tries to wire using autowire by constructor, if it does


not work, Spring tries to autowire by
byType
.

Q what Are there limitations with autowiring?


Limitations of autowiring are:
=>Overriding: You can still specify dependencies using
<constructor-arg>
and
<property>
settings which will always override autowiring.

=>Primitive data types: You cannot autowire simple properties such as primitives,
Strings, and Classes.
=>Confusing nature: Autowiring is less exact than explicit wiring, so if possible
prefer using explicit wiring.

38. How do you turn on annotation wiring?


Annotation wiring is not turned on in the Spring container by default. enable it
in our Spring
ex:configuration file by configuring

<context:annotation-config/>

Q @Required annotation
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.
40. @Autowired annotation
The
@Autowired
annotation provides more fine-grained control over where and how autowiring should
be accomplished. It can be used to autowire bean on
the setter method just like
@Required
annotation, on the constructor, on a property or pn methods with arbitrary names
and/or multiple arguments.

Q @Qualifier annotation
When there are more than one beans of the same type and only one is needed to be
wired with a property,
the @Qualifier annotation is used along with @Autowired annotation to remove the
confusion by specifying which exact bean will be wired.

66. WebApplicationContext
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.

69. @RequestMapping annotation


@RequestMapping
annotation is used to map a URL to either an entire class or a particular handler
method.
Ok, so now you are ready for your interview! Don�t forget to check our dedicated
page full of Spring Tutorials, and our Examples dedicated
subsection!

What is the difference between BeanFactory and


ApplicationContext?
BeanFactory is the basic container whereas ApplicationContext is the
advanced container. ApplicationContext extends the BeanFactory interface.
ApplicationContext provides more facilities than BeanFactory such as
integration with spring AOP, message resource handling for i18n etc.

What�s the difference between @Component, @Controller,@Repository & @Service


annotations in Spring?
>@Component is used to indicate that a class is a component. These classes are used
for auto
detection and configured as bean, when annotation based configurations are used.
DispatcherServlet is the front controller in the Spring MVC application and it
loads the spring bean
configuration file and initialize all the beans that are configured. If annotations
are enabled, it also scans
the packages and con??gure any bean annotated with @Component, @Controller,
@Repository or
@Service annotations.
ContextLoaderListener is the listener to start up and shut down Spring�s root
WebApplicationContext. It�s important functions are to tie up the lifecycle of
ApplicationContext to
the lifecycle of the ServletContext and to automate the creation of
ApplicationContext. We can use
it to de??ne shared beans that can be used across di??erent spring contexts.

23. What is ViewResolver in Spring?


ViewResolver implementations are used to resolve the view pages by name. Usually we
con??gure it in
the spring bean con??guration ??le. For example:
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in
the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
InternalResourceViewResolver is one of the implementation of ViewResolver interface
and we are
providing the view pages directory and su??x location through the bean properties.
So if a controller
handler method returns �home�, view resolver will use view page located at /WEBINF/
views/home.jsp.
24. What is a MultipartResolver and when its used?
MultipartResolver interface is used for uploading ??les � CommonsMultipartResolver
and
StandardServletMultipartResolver are two implementations provided by spring
framework for ??le
uploading. By default there are no multipart resolvers con??gured but to use them
for uploading ??les,
all we need to de??ne a bean named �multipartResolver� with type as
MultipartResolver in spring bean
con??gurations.
Once con??gured, any multipart request will be resolved by the con??gured
MultipartResolver and pass
on a wrapped HttpServletRequest. Then it�s used in the controller class to get
the ??le and process it.
For a complete example, please read Spring MVC File Upload

How to handle exceptions in Spring MVC Framework?


Spring MVC Framework provides following ways to help us achieving robust exception
handling.
Free eBook: Java Design Patterns (130 Pages) Download Now!
Your email address please..
SEND ME NOW!
11/11/2017 Spring Interview Questions and Answers - JournalDev
https://www.journaldev.com/2696/spring-interview-questions-and-answers 11/36
1. Controller Based � We can de??ne exception handler methods in our controller
classes. All we
need is to annotate these methods with @ExceptionHandler annotation.
2. Global Exception Handler � Exception Handling is a cross-cutting concern and
Spring provides
@ControllerAdvice annotation that we can use with any class to de??ne our global
exception
handler.
3. HandlerExceptionResolver implementation � For generic exceptions, most of the
times we
serve static pages. Spring Framework provides HandlerExceptionResolver interface
that we
can implement to create global exception handler. The reason behind this additional
way to
de??ne global exception handler is that Spring framework also provides default
implementation
classes that we can de??ne in our spring bean con??guration ??le to get spring
framework exception
handling bene??ts.

Can we have multiple Spring con??guration ??les?


For Spring MVC applications, we can de??ne multiple spring context con??guration ??
les through
contextConfigLocation. This location string can consist of multiple locations
separated by any
number of commas and spaces. For example;
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servletclass>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml,/WEBINF/
spring/appServlet/servlet-jdbc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
We can also de??ne multiple root level spring con??gurations and load it through
context-param. For
example;
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml /WEB-INF/spring/rootsecurity.
xml</param-value>
</context-param>
Another option is to use import element in the context con??guration ??le to import
other con??gurations,
for example:
<beans:import resource="spring-jdbc.xml"/>

How can we use Spring to create Restful Web Service returning


JSON response?
We can use Spring Framework to create Restful web services that returns JSON data.
Spring provides
integration with Jackson JSON API that we can use to send JSON response in restful
web service.
We would need to do following steps to con??gure our Spring MVC application to send
JSON response:

<artifactId>jackson-databind</artifactId>
<version>${jackson.databind-version}</version>
</dependency>

2. Con??gure RequestMappingHandlerAdapter bean in the spring bean con??guration ??


le and set the
messageConverters property to MappingJackson2HttpMessageConverter bean. Sample
con??guration will be:
3. In the controller handler methods, return the Object as response using
@ResponseBody
annotation. Sample code:
@RequestMapping(value = EmpRestURIConstants.GET_EMP, method =
RequestMethod.GET)
public @ResponseBody Employee getEmployee(@PathVariable("id") int empId) {
logger.info("Start getEmployee. ID="+empId);
return empData.get(empId);
}
4. You can invoke the rest service through any API, but if you want to use Spring
then we can easily
do it using RestTemplate class.
For a complete example, please read Spring Restful Webservice Example.
33. What are some of the important Spring annotations you have
used?
Some of the Spring annotations that I have used in my project are:
<!-- Configure to plugin JSON as request and response in method handler -->
<beans:bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHand
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jsonMessageConverter"/>
</beans:list>
</beans:property>
</beans:bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<beans:bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConver
</beans:bean>

3. In the controller handler methods, return the Object as response using


@ResponseBody
annotation. Sample code:
@RequestMapping(value = EmpRestURIConstants.GET_EMP, method =
RequestMethod.GET)
public @ResponseBody Employee getEmployee(@PathVariable("id") int empId) {
logger.info("Start getEmployee. ID="+empId);
return empData.get(empId);
}
4. You can invoke the rest service through any API, but if you want to use Spring
then we can easily
do it using RestTemplate class.
For a complete example, please read

33. What are some of the important Spring annotations you have
used?
@ResponseBody � for sending Object as response, usually for sending XML or JSON
data as
response.
@PathVariable � for mapping dynamic values from the URI to handler method
arguments.
@Autowired � for autowiring dependencies in spring beans.
@Quali??er � with @Autowired annotation to avoid confusion when multiple instances
of bean
type is present.
@Service � for service classes.
@Scope � for con??guring scope of the spring bean.
@Con??guration, @ComponentScan and @Bean � for java based con??gurations.

34. Can we send an Object as the response of Controller handler


method?
Yes we can, using @ResponseBody annotation. This is how we send JSON or XML based
response in
restful web services.

How to upload ??le in Spring MVC Application?


Spring provides built-in support for uploading ??les through MultipartResolver
interface
implementations. It�s very easy to use and requires only con??guration changes to
get it working.
Obviously we would need to write controller handler method to handle the
incoming ??le and process
it. For a complete example,

Can you explain the concept of Interceptors in Spring MVC?


Handler interceptors are used when you want to apply specific functionality to
certain requests. Handler
Interceptors should implement the interface HandlerInterceptor.
Three methods are defined:
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.

Can we have multiple Spring con??guration ??les?


YES. You can have multiple spring context ??les. There are two ways to make spring
read and con??gure them.
a) Specify all ??les in web.xml ??le using contextCon??gLocation init parameter.
b) OR, you can import them into existing con??guration ??le you have already con??
gured.
Di??erence between <context:annotation-con??g> vs
<context:component-scan>?
1) First big di??erence between both tags is that <context:annotation-config> is
used to activate applied
annotations in already registered beans in application context. Note that it simply
does not matter whether
bean was registered by which mechanism e.g. using <context:component-scan> or it
was de??ned in
application-context.xml ??le itself.
2) Second di??erence is driven from ??rst di??erence itself. It registers the beans
de??ned in con??g ??le into
context + it also scans the annotations inside beans and activate them. So
<context:component-scan> does
}
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/spring-dao-hibernate.xml,
WEB-INF/spring-services.xml,
WEB-INF/spring-security.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<beans>
<import resource="spring-dao-hibernate.xml"/>
<import resource="spring-services.xml"/>
<import resource="spring-security.xml"/>
... //Other configuration stuff
</beans>

Di??erence between @Component, @Controller, @Repository & @Service


annotations?
1) The @Component annotation marks a java class as a bean so the component-scanning
mechanism of spring
can pick it up and pull it into the application context. To use this annotation,
apply it over class as below:
2) The @Repository annotation is a specialization of the @Component annotation with
similar use and
functionality. In addition to importing the DAOs into the DI container, it also
makes the unchecked exceptions
(thrown from DAO methods) eligible for translation into Spring
DataAccessException .
3) The @Service annotation is also a specialization of the component annotation. It
doesn�t currently provide
any additional behavior over the @Component annotation, but it�s a good idea to use
@Service over
@Component in service-layer classes because it speci??es intent better.
4) @Controller annotation marks a class as a Spring Web MVC controller. It too is a
@Component
specialization, so beans marked with it are automatically imported into the DI
container. When you add the
@Controller annotation to a class, you can use another annotation i.e.
@RequestMapping ; to map URLs to
instance methods of a class.
Read More : @Component, @Repository, @Service and @Controller Annotations?
What does the ViewResolver class?
ViewResolver is an interface to be implemented by objects that can resolve views by
name. There are plenty
of ways using which you can resolve view names. These ways are supported by various
in-built
implementations of this interface. Most commonly used implementation is
InternalResourceViewResolver
class. It de??nes pre??x and su??x properties to resolve the view component.
<context:annotation-con??g> = Scanning and activating annotations in �already
registered beans�.
<context:component-scan> = Bean Registration + Scanning and activating annotations
@Component
public class EmployeeDAOImpl implements EmployeeDAO {
...
}
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>

What is a MultipartResolver and when its used?


Spring comes with MultipartResolver to handle ??le upload in web application. There
are two concrete
implementations included in Spring:
1. CommonsMultipartResolver for Jakarta Commons FileUpload
2. StandardServletMultipartResolver for Servlet 3.0 Part API
To de??ne an implementation, create a bean with the id �multipartResolver� in a
DispatcherServlet�s
application context. Such a resolver gets applied to all requests handled by that
DispatcherServlet.
If a DispatcherServlet detects a multipart request, it will resolve it via the
con??gured MultipartResolver
and pass on a wrapped HttpServletRequest. Controllers can then cast their given
request to the
MultipartHttpServletRequest interface, which permits access to any MultipartFiles .

Q How to upload file in Spring MVC Application?


Let�s say we are going to use CommonsMultipartResolver which uses the Apache
commons upload library to
handle the ??le upload in a form. So you will need to add the commons-??
leupload.jar and commons-io.jar
dependencies.
The following declaration needs to be made in the application context ??le to
enable the MultipartResolver
(along with including necessary jar ??le in the application):
Now create model class FileUploadForm which will hold the multipart data submitted
from HTML form.

Q Explain different modes of auto wiring?


� no: This is default setting. Explicit bean reference should be used for wiring.
� byName: When autowiring byName, the Spring container looks at the properties of
the beans on which autowire attribute
is set to byName in the XML configuration file. It then tries to match and wire its
properties with the beans defined by the
same names in the configuration file.
� byType: When autowiring by datatype, the Spring container looks at the properties
of the beans on which autowire
attribute is set to byType in the XML configuration file. It then tries to match
and wire a property if its type matches with
exactly one of the beans name in configuration file. If more than one such beans
exist, a fatal exception is thrown.
� constructor: This mode is similar to byType, but type applies to constructor
arguments. If there is not exactly one bean of
the constructor argument type in the container, a fatal error is raised.
� autodetect: Spring first tries to wire using autowire by constructor, if it does
not work, Spring tries to autowire by byType.

Q limitations with autowiring?


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

4.3 How do you turn on annotation wiring?


Annotation wiring is not turned on in the Spring container by default. In order to
use annotation based wiring we must enable it
in our Spring configuration file by configuring

<context:annotation-config/> element.

What is view Resolver pattern ? how it work in Spring MVC


View Resolver pattern is a J2EE pattern which allows a web application to
dynamically
choose it's view technology e.g. HTML, JSP, Tapestry, JSF, XSLT or any other view
technology. In this pattern, View resolver holds mapping of different views,
controller
return name of the view, which is then passed to View Resolver for selecting an
appropriate view. Spring MVC framework supplies inbuilt view resolver for selecting
views.

26. What�s the difference between @Component, @Controller, @Repository & @Service
annotations in Spring?
@Component: This marks a java class as a bean. It is a generic stereotype for any
Spring-managed component. The component-scanning
mechanism of spring now can pick it up and pull it into the application context.
@Controller: This marks a class as a Spring Web MVC controller. Beans marked with
it are automatically imported into the Dependency Injection container.
@Service: This annotation is a specialization of the component annotation. It
doesn�t provide any additional behavior over the @Component
annotation. You can use @Service over @Component in service-layer classes as it
specifies intent in a better way.
@Repository: This annotation is a specialization of the @Component annotation with
similar use and functionality. It provides additional benefits
specifically for DAOs. It imports the DAOs into the DI container and makes the
unchecked exceptions eligible for translation into Spring
DataAccessException.

27. What do you understand by @Required annotation?


@Required is applied to bean property setter methods. This annotation simply
indicates that bean property must be populated at the
configuration time with the help of an explicit property value in a bean definition
or with autowiring. If the affected bean property has not been populated, the
container will throw BeanInitializationException.

What do you understand by @Autowired annotation?


The @Autowired annotation provides more accurate control over where and how
autowiring should be done. This annotation is used to autowire bean on the setter
methods, constructor, a property or methods with arbitrary names or multiple
arguments.

30. What do you understand by @RequestMapping annotation?


@RequestMapping annotation is used for mapping a particular HTTP request method to
a specific class/ method in controller that will be handling
the respective request. This annotation can be applied at both levels:
Class level : Maps the URL of the request
Method level: Maps the URL as well as HTTP request method

You might also like