Spring Interview Questions and Answers
Spring Overview
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 Java EE development easier to use and promote good programming practice by enabling a POJO-based programming model.
What are important features and advantages of Springs?
Some of the features of spring framework are:
- Lightweight and very little overhead of using framework for our development.
- Dependency Injection or Inversion of Control to write components that are independent of each other, spring container takes care of wiring them together to achieve our work.
- Spring IoC container manages Spring Bean life cycle and project specific configurations such as JNDI lookup.
- Spring MVC framework can be used to create web applications as well as restful web services capable of returning XML as well as JSON response.
- Transaction Management, JDBC operations, File uploading, Exception Handling etc with very little configurations, either by using annotations or by spring bean configuration file.
Some of the advantages of using Spring Framework are:
- Reducing direct dependencies between different components of the application, usually Spring IoC container is responsible for initializing resources or beans and inject them as dependencies.
- Writing unit test cases are easy in Spring framework because our business logic doesn’t have direct dependencies with actual resource implementation classes. We can easily write a test configuration and inject our mock beans for testing purposes.
- Reduces the amount of boiler-plate code, such as initializing objects, open/close resources. For example JdbcTemplate class helps us in removing all the boiler-plate code that comes with JDBC programming.
- Spring framework is divided into several modules, it helps us in keeping our application lightweight. For example, if we don’t need Spring transaction management features, we don’t need to add that dependency in our project.
What is Spring IoC Container?
Inversion of Control (IoC) is the mechanism to achieve loose-coupling between Objects dependencies. To achieve loose coupling and dynamic binding of the objects at runtime, the objects define their dependencies that are being injected by other assembler objects. Spring IoC container is the program that injects dependencies into an object and make it ready for our use.
Spring Framework IoC container classes are part of org.springframework.beans and org.springframework.context packages and provides us different ways to decouple the object dependencies.
Some of the useful ApplicationContext implementations that we use are;
- AnnotationConfigApplicationContext: For standalone java applications using annotations based configuration.
- ClassPathXmlApplicationContext: For standalone java applications using XML based configuration.
- FileSystemXmlApplicationContext: Similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
- AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.
What are the common implementations of the ApplicationContext?
Below are 3 different implementations of ApplicationContext:
- 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.
- 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.
- WebXmlApplicationContext: container loads the XML file with definitions of all beans from within a web application.
What is the difference between Bean Factory and ApplicationContext?
In Short: use an ApplicationContext unless you have a really good reason for not doing so. For those of you that are looking for slightly more depth as to the ‘but why’ of the above recommendation, keep reading.
As the ApplicationContext includes all functionality of the BeanFactory, it is generally recommended that it be used in preference to the BeanFactory, except for a few limited situations such as in an Applet, where memory consumption might be critical and a few extra kilobytes might make a difference.
Find below a feature matrix that lists what features are provided by the BeanFactory and ApplicationContext interfaces
Features |
BeanFactory |
ApplicationContext |
Bean instantiation/wiring |
Yes |
Yes |
Automatic BeanPostProcessor registration |
No |
Yes |
Automatic BeanFactoryPostProcessor registration |
No |
Yes |
Convenient MessageSource access (for i18n) |
No |
Yes |
ApplicationEvent publication |
No |
Yes |
Dependency Injection
What are the types of Dependency Injection supported by Spring?
- Setter Injection : Setter-based DI is realized by calling setter methods on the user’s beans after invoking a no-argument constructor or no-argument static factory method to instantiate their bean.
- Constructor Injection : Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator.
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.
Spring Beans
What are Spring beans?
The objects that form the backbone of the users 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 the users supply to the container.
What are the different bean scopes does Spring support?
The Spring Framework supports following five scopes, three of which are available only if the users use a web-aware Application Context.
- Singleton: This scopes the bean definition to a single instance per Spring IoC container.
- Prototype: This scopes a single bean definition to have any number of object instances.
- Request: This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext
- Session: This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
- Global-session: This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
What is Bean lifecycle in Spring framework?
Spring bean lifecycle is managed in below order:
- Instantiate: First the spring container finds the bean’s definition from the XML file and loads the bean.
- Populate properties: Using the dependency injection, spring populates all of the properties as specified in the bean definition.
- Set Bean Name: If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.
- Set Bean factory: If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
- Pre Initialization: Also called post process of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
- Initialize beans: If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
- Post Initialization: – If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
- Ready to use: Now the bean is ready to use by the application
- Destroy: If the bean implements DisposableBean , it will call the destroy() method
What are different ways to configure a class as Spring Bean?
There are three different ways to configure Spring Bean.
- XML Configuration: This is the most popular configuration and we can use bean element in context file to configure a Spring Bean. For example:
1 |
<bean name="myBean" class="com.learningsolo.spring.beans.MyBean"/> |
- Java Based Configuration: If you are using only annotations, you can configure a Spring bean using @Bean annotation. This annotation is used with @Configuration classes to configure a spring bean. Sample configuration is:
1 2 3 4 5 6 7 8 |
@Configuration @ComponentScan(value="com.learningsolo.spring.main") public class MyConfiguration { @Bean public MyService getService(){ return new MyService(); } } |
To get this above bean from spring context, we need to use following code snippet:
1 2 |
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfiguration.class); MyService service = ctx.getBean(MyService.class); |
3. Annotation Based Configuration: We can also use @Component, @Service, @Repository and @Controller annotations with classes to configure them to be as spring bean. For these, we would need to provide base package location to scan for these classes. For example:
1 |
<context:component-scan base-package="com.learningsolo.spring*" /> |
Are Singleton beans thread safe in Spring Framework?
No Singleton bean in Spring is not Thread Safe. The two concepts are not even related.
Singletons are about creation. This design pattern ensures that only one instance of a class is created at any point of time. Spring just manage the life cycle of singleton bean and maintains single instance of object.
Thread safety is about execution. Eventually thread safety depends on the code and the code only. And this is the reason why Spring beans are not thread safe.
What are inner beans in Spring?
When a bean is only used as a property of another bean it can be declared as an inner bean. Spring’s XML-based configuration metadata provides the use of <bean/> element inside the <property/> or <constructor-arg/> elements of a bean definition, in order to define the so-called inner bean. Inner beans are always anonymous and they are always scoped as prototypes.
How to 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.
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.
What are the 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.
Is it possible to inject null and empty string values in Spring?
Yes, you can.
How to get ServletContext and ServletConfig object in a Spring Bean?
There are two ways to get Container specific objects in the spring bean.
- Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces.
- Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet container specific environment only through.
1 2 |
@Autowired ServletContext servletContext; |
Spring Annotations
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.
An example is @Configuration annotation, that indicates that the class can be used by the Spring IoC container as a source of bean definitions. Another example is the@Bean annotated method that will return an object that should be registered as a bean in the Spring application context.
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. In order to use annotation based wiring we must enable it in our Spring configuration file by configuring <context:annotation-config/> element.
Whats is the purpose of @Required, @Autowaired & @Qualifier annotations ?
- @Required : 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.
- @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.
- @Qualifier : When there are more than one beans of the same type and only one is needed to be wired with a property, the @Qualifierannotation is used along with @Autowired annotation to remove the confusion by specifying which exact bean will be wired.
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.
- @Controller is a specific type of component, used in MVC applications and mostly used with RequestMapping annotation.
- @Repository annotation is used to indicate that a component is used as repository and a mechanism to store/retrieve/search data. We can apply this annotation with DAO pattern implementation classes.
- @Service is used to indicate that a class is a Service. Usually the business facade classes that provide some services are annotated with this.
Spring Aspect Oriented Programming (AOP)
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.
Whats is Aspect?
The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. It is a module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement. In Spring AOP, aspects are implemented using regular classes annotated with the @Aspect annotation (@AspectJ style).
What do you understand by Aspect Oriented Programming?
Enterprise applications have some common cross-cutting concerns that is applicable for different types of Objects and application modules, such as logging, transaction management, data validation, authentication etc. In Object Oriented Programming, modularity of application is achieved by Classes whereas in AOP application modularity is achieved by Aspects and they are configured to cut across different classes methods.
AOP takes out the direct dependency of cross-cutting tasks from classes that is not possible in normal object oriented programming. For example, we can have a separate class for logging but again the classes will have to call these methods for logging the data.
What is Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?
- Aspect: Aspect is a class that implements cross-cutting concerns, such as transaction management. Aspects can be a normal class configured in Spring Bean configuration file or we can use Spring AspectJ support to declare a class as Aspect using @Aspect annotation.
- Advice: Advice is the action taken for a particular join point. In terms of programming, they are methods that gets executed when a specific join point with matching pointcut is reached in the application. You can think of Advice as Spring interceptors or Servlet Filters.
- Pointcut: Pointcut are regular expressions that is matched with join points to determine whether advice needs to be executed or not. Spring framework uses the AspectJ pointcut expression language for determining the join points where advice methods will be applied.
- Join Point: A join point is the specific point in the application such as method execution, exception handling, changing object variable values etc. In Spring AOP a join points is always the execution of a method.
- Advice Arguments: We can pass arguments in the advice methods. We can use args() expression in the pointcut to be applied to any method that matches the argument pattern. If we use this, then we need to use the same name in the advice method from where argument type is determined.
What is the difference between Spring AOP and AspectJ AOP?
AspectJ is the industry-standard implementation for Aspect Oriented Programming whereas Spring implements AOP for some cases. Main differences between Spring AOP and AspectJ are:
- Spring AOP is simpler to use than AspectJ because we don’t need to worry about the weaving process.
- Spring AOP supports AspectJ annotations, so if you are familiar with AspectJ then working with Spring AOP is easier.
- Spring AOP supports only proxy-based AOP, so it can be applied only to method execution join points. AspectJ support all kinds of pointcuts.
- One of the shortcoming of Spring AOP is that it can be applied only to the beans created through Spring Context.
What is Advice?
The advice is the actual action that will be taken either before or after the method execution. This is actual piece of code that is invoked during the program execution by the Spring AOP framework.
Spring aspects works with five kinds of advice:
- before: Run advice before the a method execution.
- after: Run advice after the a method execution regardless of its outcome.
- after-returning: Run advice after the a method execution only if method completes successfully.
- after-throwing: Run advice after the a method execution only if method exits by throwing an exception.
- around: Run advice before and after the advised method is invoked.
What is Weaving? What are the different points where weaving can be applied?
Weaving is the process of linking aspects with other application types or objects to create an advised object.Weaving can be done at compile time, at load time, or at runtime.
Spring Model View Controller (MVC)
What is Spring MVC framework?
Spring comes with a full-featured MVC framework for building web applications. Although Spring can easily be integrated with other MVC frameworks, such as Struts, Spring’s MVC framework uses IoC to provide a clean separation of controller logic from business objects. It also allows to declaratively bind request parameters to business objects.
What is a Controller in Spring MVC?
Just like MVC design pattern, Controller is the class that takes care of all the client requests and send them to the configured resources to handle it. In Spring MVC, org.springframework.web.servlet.DispatcherServlet is the front controller class that initializes the context based on the spring beans configurations. A Controller class is responsible to handle different kind of client requests based on the request mappings. We can create a controller class by using @Controller annotation. Usually it’s used with @RequestMapping annotation to define handler methods for specific URI mapping.
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.
- @Controller is a specific type of component, used in MVC applications and mostly used with RequestMapping annotation.
- @Repository annotation is used to indicate that a component is used as repository and a mechanism to store/retrieve/search data. We can apply this annotation with DAO pattern implementation classes.
- @Service is used to indicate that a class is a Service. Usually the business facade classes that provide some services are annotated with this.
What is DispatcherServlet and ContextLoaderListener?
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 configure 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 define shared beans that can be used across different spring contexts.
What is ViewResolver in Spring?
ViewResolver are used to resolve the view pages by name. Usually we configure it in the spring bean configuration file. For example:
1 2 3 4 5 |
<!-- 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. prefix defines view pages directory and suffix location through the bean properties. So if a controller handler method returns “home”, view resolver will use view page located at /WEB-INF/views/home.jsp.
For a complete example, please read Spring MVC InternalResourceViewResolver example
What is a MultipartResolver and when its used?
MultipartResolver interface is used for uploading files – CommonsMultipartResolver and StandardServletMultipartResolver are two implementations provided by spring framework for file uploading. By default there are no multipart resolvers configured but to use them for uploading files, all we need to define a bean named “multipartResolver” with type as MultipartResolver in spring bean configurations.
Once configured, any multipart request will be resolved by the configured MultipartResolver and pass on a wrapped HttpServletRequest. Then it’s used in the controller class to get the file and process it. For a complete example, please read Spring MVC File Upload Example.
How to handle exceptions in Spring MVC Framework?
Spring MVC Framework provides following ways to achieve robust exception handling.
- Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
- Global Exception Handler – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
- 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 define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.
How to create ApplicationContext in a Java Program?
There are following ways to create spring context in a standalone java program.
- AnnotationConfigApplicationContext: If we are using Spring in standalone java applications and using annotations for Configuration, then we can use this to initialize the container and get the bean objects.
- ClassPathXmlApplicationContext: If we have spring bean configuration xml file in standalone application, then we can use this class to load the file and get the container object.
- FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
Can we have multiple Spring configuration files?
Yes, For Spring MVC applications, we can define multiple spring context configuration files through contextConfigLocation. This location string can consist of multiple locations separated by any number of commas and spaces. For example;
1 2 3 4 5 6 7 8 9 |
<servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml,/WEB-INF/spring/appServlet/servlet-jdbc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> |
We can also define multiple root level spring configurations and load it through context-param. For example;
1 2 3 4 |
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml /WEB-INF/spring/root-security.xml</param-value> </context-param> |
Another option is to use import element in the context configuration file to import other configurations, for example:
1 |
<beans:import resource="spring-jdbc.xml"/> |
What is ContextLoaderListener?
ContextLoaderListener is the listener class used to load root context and define spring bean configurations that will be visible to all other contexts. It’s configured in web.xml file as:
1 2 3 4 5 6 7 8 |
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> |
What are the minimum configurations needed to create Spring MVC application?
For creating a simple Spring MVC application, we would need to do following steps
- Add spring-context and spring-webmvc dependencies in the project.
- Configure DispatcherServlet in the web.xml file to handle requests through spring container.
- Spring bean configuration file to define beans, if using annotations then it has to be configured here. Also we need to configure view resolver for view pages.
- Controller class with request mappings defined to handle the client requests.
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.
How to achieve localization in Spring MVC applications?
Spring provides excellent support for localization or i18n through resource bundles. Basis steps needed to make our application localized are:
- Creating message resource bundles for different locales, such as messages_en.properties, messages_fr.properties etc.
- Defining messageSource bean in the spring bean configuration file of type ResourceBundleMessageSource or ReloadableResourceBundleMessageSource.
- For change of locale support, define localeResolver bean of type CookieLocaleResolver and configure LocaleChangeInterceptor interceptor. Example configuration can be like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <beans:property name="basename" value="classpath:messages" /> <beans:property name="defaultEncoding" value="UTF-8" /> </beans:bean> <beans:bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"> <beans:property name="defaultLocale" value="en" /> <beans:property name="cookieName" value="myAppLocaleCookie"></beans:property> <beans:property name="cookieMaxAge" value="3600"></beans:property> </beans:bean> <interceptors> <beans:bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <beans:property name="paramName" value="locale" /> </beans:bean> </interceptors> |
Use spring:message element in the view pages with key names, DispatcherServlet picks the corresponding value and renders the page in corresponding locale and return as response.
What are some of the important Spring annotations that are frequently used?
Some of the Spring annotations that I have used in my project are:
- @Controller – for controller classes in Spring MVC project.
- @RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation, so you should go through Spring MVC RequestMapping Annotation Examples
- @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.
- @Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.
- @Service – for service classes.
- @Scope – for configuring scope of the spring bean.
- @Configuration, @ComponentScan and @Bean – for java based configurations.
Can we send an Custom 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 file in Spring MVC Application?
Spring provides built-in support for uploading files through MultipartResolver interface implementations. It’s very easy to use and requires only configuration changes to get it working. Obviously we would need to write controller handler method to handle the incoming file and process it.
1 2 3 4 |
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- Maximum upload file size --> <beans:property name="maxUploadSize" value="100000" /> </beans:bean> |
Add MultiPartFile in you controller method parameter
1 2 3 4 5 6 7 8 9 10 |
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public @ResponseBody String uploadFileHandler(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) { ..... } <span style="color: #000000;">For a complete example, please read <a href="https://learningsolo.com/spring-mvc-file-upload-example-tutorial/">Spring MVC File Upload Example.</a></span> |
How to validate form data in Spring Web MVC Framework?
Spring supports JSR-303 annotation based validations as well as provide Validator interface that we can implement to create our own custom validator. For using JSR-303 based validation, we need to annotate bean variables with the required validations.
What are 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.
The handler interceptor have to implement the HandlerInterceptor interface, which contains three methods :
- preHandle() – Called before the handler execution, returns a boolean value, “true” : continue the handler execution chain; “false”, stop the execution chain and return it.
- postHandle() – Called after the handler execution, allow manipulate the ModelAndView object before render it to view page.
- afterCompletion() – Called after the complete request has finished. Seldom use, cant find any use case.
What is a Spring Application Context? What are some example usages of one?
An ApplicationContext is an interface extending BeanFactory’s functionality. In addition to the BeanFactory’s methods, ApplicationContext provides the ability to:
- Load file resources by extending the ResourcePatternResolver interface
- Publish events to registered listeners (via the ApplicationEventPublisher interface)
- Resolve messages supporting internationalization (with the MessageSource interface).
It’s read-only while the application is running. The easiest way to create an ApplicationContent instance is:
1 2 3 |
ApplicationContext ctx = new FileSystemXmlApplicationContext("application.xml"); ctx.getResources(String locationPattern); ctx.getResource(String location); |
Also to Access the application context, There are a few methods for obtaining a reference to the application context. You can implement ApplicationContextAware as in the following example:
1 2 3 4 5 6 7 8 |
public class A implements ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } } |
How do you load and inject properties into a Spring Bean?
Let’s say we have a message.properties file that defines a database connection timeout property called connection.timeout. To load this property into a Spring context, we need to define a propertyConfigurer bean:
1 2 3 |
<bean id="propertyConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> <property name="location" value="/WEB-INF/message.properties" /> </bean> |
After that we can use Spring Expression Language to inject properties into other beans:
1 2 3 |
<bean class="com.learningsolo.spring.ConnectionFactory"> <property name="timeout" value="${connection.timeout}"/> </bean> |
The same is available in the annotation based configuration, like so:
1 2 |
@Value("${connection.timeout}") private int timeout; |
What are the different ways to configure a class as Spring Bean?
There are multiple ways to configure Spring Bean: XML configuration, Java based configuration and annotation based configuration.
- XML configuration
1 |
<bean id="myBean" class="com.learningsolo.spring.MyBean"/> |
- Java Based Configuration
1 2 |
ConfigurableApplicationContext context; context.getBeanFactory().registerSingleton(name, obj); |
- Annotation Based Configuration
A Spring Bean can be configured with the @Bean annotation, which is used together with @Configuration classes.
1 2 3 4 5 6 7 |
@Configuration public class MyConfiguration { @Bean public MyService getService(){ return new MyService(); } } |
- Annotations Based : Annotations @Component, @Service, @Repository and @Controller can also be used with classes to configure them as Spring Beans. In this case, the base package location has to be provided to scan for these classes, like so:
<context:component-scan base-package=”com.learningsolo.spring” />
Spring Data Access
How can JDBC be used more efficiently in the Spring framework?
When using the Spring JDBC framework the burden of resource management and error handling is reduced. So developers only need to write the statements and queries to get the data to and from the database. JDBC can be used more efficiently with the help of a template class provided by Spring framework.
- JdbcTemplate : JdbcTemplate class provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling.
- Spring DAO support : The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows us to switch between the persistence technologies fairly easily and to code without worrying about catching exceptions that are specific to each technology.
How would you achieve Transaction Management in Spring?
Spring framework provides transaction management support through Declarative Transaction Management as well as programmatic transaction management. Declarative transaction management is most widely used because it’s easy to use and works in most of the cases.
We use annotate a method with @Transactional annotation for Declarative transaction management. We need to configure transaction manager for the DataSource in the spring bean configuration file.
1 2 3 |
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> |
How to use Tomcat JNDI DataSource in Spring Web Application?
For using servlet container configured JNDI DataSource, we need to configure it in the spring bean configuration file and then inject it to spring beans as dependencies. Then we can use it with JdbcTemplate to perform database operations.
Sample configuration would be:
1 2 3 |
<beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/> </beans:bean> |
What are the benefits of the Spring Framework’s transaction management?
The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits:
- Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
- Supports declarative transaction management.
- Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
- Integrates very well with Spring’s various data access abstractions.
Spring resolves the disadvantages of global and local transactions. It enables application developers to use a consistent programming model in any environment. You write your code once, and it can benefit from different transaction management strategies in different environments. The Spring Framework provides both declarative and programmatic transaction management.