What are the different types of events provided by Spring framework?

Spring framework provides following five events for Context:

  • ContextRefreshedEvent: Whenever ApplicationContext is initialized or refreshed, Spring publishes this event. We can also raise it by using refresh() method on ConfigurableApplicationContext interface.
  • ContextStartedEvent: When ApplicationContext is started using start() method on ConfigurableApplicationContext interface, ContextStartedEvent is published. We can poll database or restart any stopped application after receiving this event.
  • ContextStoppedEvent: Spring publishes this event when ApplicationContext is stopped using stop() method on ConfigurableApplicationContext interface. This is used for doing any cleanup work.
  • ContextClosedEvent: Once the ApplicationContext is closed using close() method, ContextClosedEvent is published. Once a context is closed, it is the last stage of its lifecycle. After this it cannot be refreshed or restarted.
  • RequestHandledEvent: This is a web specific event that informs to all beans that an HTTP request has been serviced.

What is the difference between DispatcherServlet and ContextLoaderListener in Spring?

  • DispatcherServlet is the core of Spring MVC application. It loads Spring bean configuration file and initialize all the beans mentioned in config file.
  • In case we have enabled annotations in Spring config file, it also scans the packages and configures any bean annotated with @Component, @Controller, @Repository or @Service annotations.
  • ContextLoaderListener is a listener to start up and shut down Spring’s root WebApplicationContext. ContextLoaderListener links the lifecycle of ApplicationContext to the lifecycle of the ServletContext. It automates the creation of ApplicationContext. It can also be used to define shared beans used across different spring contexts.

How will you handle exceptions in Spring MVC Framework?

Spring MVC Framework provides following mechanisms to help us achieve exception handling:

<li><strong>Controller Based</strong>: A developer can define exception handler methods in a Controller class. To do so, they have to annotate the methods with @ExceptionHandler annotation.</li>

<li><strong>Global Exception Handler</strong>: Spring provides @ControllerAdvice annotation for exception handling as cross-cutting concern. We can mark any class as global exception handler by using this annotation.</li>

<li><strong>HandlerExceptionResolver implementation</strong>: Spring Framework provides HandlerExceptionResolver interface that can be implemented to create a global exception handler. </li>

What are the best practices of Spring Framework?

In Spring Framework, following are some of the best practices:

  • We can Divide spring bean configurations based on their concerns such as spring-jdbc.xml, spring-security.xml.
  • It is better to avoid version numbers in schema reference. This makes sure that we have the latest config files.
  • It is a good practice to configure bean dependencies as much as possible. Unless there is a good reason, we try to avoid autowiring.
  • For spring beans that are used in multiple contexts in Spring MVC, we can create them in root context and initialize with listener.
  • Spring framework provides many features and modules. We should just use what we need for our application. An extra dependency has to be removed
  • For application properties, it is good to create a property file and read it in Spring configuration file.
  • Annotations are useful for smaller applications, but for larger applications annotations can become an overhead. It is easier to maintain if all the configurations are in xml files.
  • When we are doing AOP, we have to make sure to keep the Joinpoint as narrow as possible to avoid Advice on unwanted methods.
  • We should use right annotation for components or services. For services use @Service and for DAO beans use @Repository.
  • Dependency Injection (DI) has to be used when there is real benefit. It should not be used just for the sake of loose coupling.

What is Spring Boot?

Spring Boot is a ready made solution to create Spring applications with production grade features. It favors convention over configuration.

We can embed Tomcat or Jetty in in an application created with Spring Boot. Spring Boot automatically configures Spring in an application.

It does not require any code generation or xml configuration. It is an easy solution to create applications that can run stand-alone.

What are the differences between Dependency Injection (DI) and Factory Pattern?

Main differences between Dependency Injection (DI) and Factory Pattern are:

  • Coupling: Factory pattern adds tight coupling between an object, factory and dependency. In case of DI, there is no coupling between objects. We just mention the dependencies on different objects and container resolves and introduces these dependencies.
  • Easier Testing: DI is easier to test, since we can inject the mock objects as dependency in Test environment. In case of Factory pattern, we need to create actual objects for testing.
  • Flexibility: DI allows for switching between different DI frameworks easily. It gives flexibility in the choice of DI framework.
  • Container: DI always needs a container for injecting the dependencies. This leads to extra overhead as well as extra code in your application. In factory pattern, you can just use POJO classes to implement the application without any container.
  • Cleaner Code: DI code is much cleaner than Factory pattern based code. In DI, we do not need to add extra code for factory methods.

In Spring framework, what is the difference between FileSystemResource and ClassPathResource?

In Spring we can specify configuration by using a file or classpath.

<li>In FileSystemResource we have to give absolute path / relative path of Spring Configuration file spring-config.xml file.</li>

<li>In ClassPathResource Spring looks for Spring Configuration file spring-config.xml in ClassPath. Therefore, developer has to include spring-config.xml in classpath.</li>

<li>ClassPathResource looks for configuration file in CLASSPATH, whereas FileSystemResource looks for configuration file in file system.</li>

Name some popular Spring framework annotations that you use in your project?

Spring has many Annotations to serve different purposes. For regular use we refer following popular Spring annotations:

  • @Controller: This annotation is for creating controller classes in a Spring MVC project.
  • @RequestMapping: This annotation maps the URI to a controller handler method in Spring MVC.
  • @ResponseBody: For sending an Object as response we use this annotation.
  • @PathVariable: To map dynamic values from a URI to handler method arguments, we use this annotation.
  • @Autowired: This annotation indicates to Spring for auto-wiring dependencies in beans.
  • @Service: This annotation marks the service classes in Spring.
  • @Scope: We can define the scope of Spring bean by this annotation.
  • @Configuration: This an annotation for Java based Spring configuration.
  • @Aspect, @Before, @After, @Around, @Joinpoint, @Pointcut: These are the annotations in Spring for AspectJ AOP.

How can you upload a file in Spring MVC Application?

In Spring MVC framework we can use MultipartResolver interface to upload a file. We need to make configuration changes to make it work. After uploading the file, we have to create Controller handler method to process the uploaded file in application.

What is @RequestMapping annotation in Spring?

  • In Spring MVC, we use @RequestMapping annotation to map a web request to either a class or a handler method.
  • In @RequestMapping we can specify the path of URL as well as HTTP method like- GET, PUT, POST etc.
  • @RequestMapping also supports specifying HTTP Headers as attributes.
  • We can also map different media types produced by a controller in @RequestMapping. We use HTTP Header Accepts for this purpose.
  • E.g. @RequestMapping(
    value = “/test/mapping”,
    method = GET,
    headers = “Accept=application/json”)