Filters

  1. A filter as the name suggests is a Java class executed by the servlet container for each incoming http request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same way is possible to manage HTTP outbound response after resource execution.
  2. The filter runs in the web container so its definition will also be contained in the web.xml file
  3. filer include three main methods:
    • init: executed to initialize filter using init-param element in filter definition
    • doFilter: executed for all HTTP incoming request that satisfy “url-pattern”
    • release resources used by the filter

web.xml

<filter>
    <filter-name>CORSFilter</filter-name>
    <filter-class>com.listfeeds.components.CORSFilter</filter-class>
    <init-param>
        <param-name>fake-param</param-name>
        <param-value>fake-param-value</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

TestFilter.java

package com.listfeeds.filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

public class TestFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

Filters can perform many different types of functions.

  1. Authentication-Blocking requests based on user identity.
  2. Logging and auditing-Tracking users of a web application.
  3. Image conversion-Scaling maps
  4. Data compression-Making downloads smaller
  5. Localization-Targeting the request and response to a particular locale

Request Filters can:

  1. perform security checks
  2. reformat request headers or bodies
  3. audit or log requests

Response Filters can:

  1. Compress the response stream
  2. Append or alter the response stream
  3. Create a different response altogether

Interceptors

  1. Spring Interceptors are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sophisticated behavior because can access to all Spring context.
  2. Developers can invoke interceptor methods in conjunction with method invocations or lifecycle events on an associated target class. Common uses of interceptors are logging, auditing, or profiling.
  3. Spring interceptor execute in Spring context so they have be defined in rest-servlet.xml file:
  4. The interceptor include three main methods:
    • preHandle: executed before the execution of the target resource
    • afterCompletion: executed after the execution of the target resource (after rendering the view)
    • posttHandle: Intercept the execution of a handler

rest-servlet.xml

<mvc:interceptors>
    <bean class="com.listfeeds.interceptors.LogContextInterceptor" />
    <bean class="com.listfeeds.interceptors.TimedInterceptor" />
</mvc:interceptors>

LogContextInterceptor.java

public class LogContextInterceptor extends HandlerInterceptorAdapter 
{
 private static final Logger log = LoggerFactory.getLogger(LogContextInterceptor.class);

 @Override
 public void afterCompletion(
  HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
 throws Exception 
 {
  HandlerMethod methodHandler = (HandlerMethod) handler;
  log.debug("END EXECUTION method {} request: {}", methodHandler.getMethod().getName(), request.getRequestURI());
  }
 

 @Override
 public boolean preHandle(HttpServletRequest request,
  HttpServletResponse response, Object handler) throws Exception 
  {

  } catch (IllegalArgumentException e) 
  {
   log.warn("Prehandle", e);
   return true;
  } finally 
  {
   HandlerMethod methodHandler = (HandlerMethod) handler;
   log.debug("START EXECUTION method {} request: {}", methodHandler.getMethod().getName(), request.getRequestURI());
  }
  return true;
}

For authentication of web pages you would use a servlet filter which acts at weblayer. For security stuff in your business layer or logging/bugtracing (a.k.a. independent of the web layer) you would use an Interceptor.

Q1.What is the Difference between Filters and Interceptors?
Filter: – A filter as the name suggests is a Java class executed by the servlet container for each incoming HTTP request and for each http response. This way, is possible to manage HTTP incoming requests before they reach the resource, such as a JSP page, a servlet or a simple static page; in the same way, it’s possible to manage HTTP outbound response after resource execution.

  1. A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses.
  2. Filters typically do not themselves create a response, but instead provide universal functions that can be “attached” to any type of servlet or JSP page.
  3. They provide the ability to encapsulate recurring tasks in reusable units. Organized developers are constantly on the lookout for ways to modularize their code.
  4. Modular code is more manageable and documentable, is easier to debug, and if done well, can be reused in another setting.

Interceptor: – Spring Interceptors are similar to Servlet Filters but they act in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sophisticated behavior because can access to all Spring context. Interceptors are used in conjunction with Java EE managed classes to allow developers to invoke interceptor methods in conjunction with method invocations or lifecycle events on an associated target class. Common uses of interceptors are logging, auditing, or profiling.

  1. Interceptor can be defined within a target class as an interceptor method, or in an associated class called an interceptor class.
  2. Interceptor classes contain methods that are invoked in conjunction with the methods or lifecycle events of the target class.
  3. Interceptor classes and methods are defined using metadata annotations, or in the deployment descriptor of the application containing the interceptors and target classes.
  4. Interceptor classes may be targets of dependency injection. Dependency injection occurs when the interceptor class instance is created, using the naming context of the associated target class, and before any @PostConstruct callbacks are invoked.

Refer Here

Q2.Spring interceptor vs servlet filter?

  1. Using Interceptor we can inject other beans in the interceptor
  2. Can use more advanced mapping patterns (ant-style)
  3. You have the target handler object (controller) available, as well as the result ModelAndView
  4. It is a bean, so you can use AOP with it (althoug that would be rare)

Q3.How to avoid multiple submission of Form to Server?

  1. Use JavaScript to disable the button a few ms after click. This will avoid multiple submits being caused by impatient users clicking multiple times on the button.
  2. Send a redirect after submit, this is known as Post-Redirect-Get (PRG) pattern. This will avoid multiple submits being caused by users pressing F5 on the result page and ignoring the browser warning that the data will be resend, or navigating back and forth by browser back/forward buttons and ignoring the same warning.
  3. Generate an unique token when the page is requested and put in both the session scope and as hidden field of the form. During processing, check if the token is there and then remove it immediately from the session and continue processing. If the token is not there, then block processing. This will avoid the aforementioned kinds of problems.

Q4.What is POST-REDIRECT-GET Pattern?
The client gets a page with a form.The form POSTs to the server.The server performs the action, and then redirects to another page.The client follows the redirect.
For example, say we have this structure of the website as below

  1. /posts (shows a list of posts and a link to “add post”) and / (view a particular post)
  2. /create (if requested with the GET method, returns a form posting to itself; if it’s a POST request, creates the post and redirects to the / endpoint)

For retrieving posts /posts/ might be implemented like this:

  1. Find the post with that ID in the database.
  2. Render a template with the content of that post.

For creating posts /posts/create might be implemented like this:

  1. If the request is a GET request for the Insert posts page Show an empty form with the target set to itself and the method set to POST.
  2. If the request is a POST request
    • Validate the fields.
    • If there are invalid fields, show the form again with errors indicated.
  3. Otherwise, if all fields are valid
    • Add the post to the database.
    • Redirect to /posts/ (where is returned from the call to the database)

null

A Bean definition contains the following piece of information called configuration metadata, which helps the container know the following things.

• The way a bean should be created.
• Life cycle details of a bean.
• Associated Bean dependencies.

The above metadata for the bean configuration is provided as a set of properties or attributes in an XML file (configuration file) which together prepare a bean definition. The following are the set of properties.

Properties Usage
class In a bean definition, it is a mandatory attribute. It is used to specify the bean class which can be used by the container to create the bean.
name In a bean definition, this attribute is used to specify the bean identifier uniquely. In XML based configuration metadata for a bean, we use the id and/or name attributes in order to specify the bean identifier(s).
scope This attribute is used to specify the scope of the objects which are created from a particular bean definition.
constructor-arg In a bean definition, this attribute is used to inject the dependencies.
properties In a bean definition, this attribute is used to inject the dependencies.
autowiring mode In a bean definition, this attribute is used to inject the dependencies.
lazy-initialization mode In a bean definition, a lazy-initialized bean informs the IoC container to create a bean instance only when it is first requested, instead of startup.
initialization method In a bean definition, a callback to be called after all required properties on the bean have been set up by the container.
destruction method In a bean definition, a callback to be used when the container that contains the bean is destroyed.

In the following example, we are going to look into an XML based configuration file which has different bean definitions. The definitions include lazy initialization (lazy-init), initialization method (init-method), and destruction method (destroy-method) as shown below. This configuration metadata file can be loaded either through BeanFactory or ApplicationContext

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <!-- A simple bean definition -->
   <bean id = "..." class = "...">
      <!— Here will be collaborators and configuration for this bean -->
   </bean>

   <!-- A bean definition which has lazy init set on -->
   <bean id = "..." class = "..." lazy-init = "true">
      <!-- Here will be collaborators and configuration for this bean -->
   </bean>

   <!-- A bean definition which has initialization method -->
   <bean id = "..." class = "..." init-method = "...">
      <!-- Here will be collaborators and configuration for this bean -->
   </bean>

   <!-- A bean definition which has destruction method -->
   <bean id = "..." class = "..." destroy-method = "...">
      <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- more bean definitions can be written below -->
   
</beans>

Q1.What is the Difference between applicationContext and BeanFactory?
ApplicationContext is more feature rich container implementation and should be favored over BeanFactory.Both BeanFactory and ApplicationContext provides a way to get a bean from Spring IOC container by calling getBean(“bean name”)

  1. Bean factory instantiate bean when you call getBean() method while ApplicationContext instantiates Singleton bean when the container is started, It doesn’t wait for getBean to be called.
  2. BeanFactory provides basic IOC and DI features while ApplicationContext provides advanced features
  3. ApplicationContext is ability to publish event to beans that are registered as listener.
  4. implementation of BeanFactory interface is XMLBeanFactory while one of the popular implementation of ApplicationContext interface is ClassPathXmlApplicationContext.In web application we use we use WebApplicationContext which extends ApplicationContext interface and adds getServletContext method
  5. ApplicationContext provides Bean instantiation/wiring,Automatic BeanPostProcessor registration, Automatic BeanFactoryPostProcessor registration,Convenient MessageSource access and ApplicationEvent publication whereas BeanFactory provides only Bean instantiation/wiring

null

Q2.What is the Difference between Component and Bean?

  1. @Component auto detects and configures the beans using classpath scanning whereas @Bean explicitly declares a single bean, rather than letting Spring do it automatically.
  2. @Component does not decouple the declaration of the bean from the class definition where as @Bean decouples the declaration of the bean from the class definition.
  3. @Component is a class level annotation where as @Bean is a method level annotation and name of the method serves as the bean name.
  4. @Component need not to be used with the @Configuration annotation where as @Bean annotation has to be used within the class which is annotated with @Configuration.
  5. We cannot create a bean of a class using @Component, if the class is outside spring container whereas we can create a bean of a class using @Bean even if the class is present outside the spring container.
  6. @Component has different specializations like @Controller, @Repository and @Service whereas @Bean has no specializations.

@Component (and @Service and @Repository) are used to auto-detect and auto-configure beans using classpath scanning. There’s an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class). Control of wiring is quite limited with this approach since it’s purely declarative.

@Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically as above. It decouples the declaration of the bean from the class definition and lets you create and configure beans exactly how you choose.

Let’s imagine that you want to wire components from 3rd-party libraries (you don’t have the source code so you can’t annotate its classes with @Component), where an automatic configuration is not possible.The @Bean annotation returns an object that spring should register as a bean in the application context. The body of the method bears the logic responsible for creating the instance.
@Bean is applicable to methods, whereas @Component is applicable to types

Q3.What is the difference between @Configuration and @Component in Spring?
@Configuration Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime

@Component Indicates that an annotated class is a “component”. Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

@Configuration is meta-annotated with @Component, therefore @Configuration classes are candidates for component scanning

Q4.Life cycle of Spring Bean

  1. There are five methods called before bean comes to ready state
  2. BeanPostProcessor method – postProcessBeforeInitilaization and postProcessAfterInitilaization would be called between init method(3 methods)
  3. After postProcessBeforeInitilaization @postContruct and afterPropertiesSet method would be called(2 methods)
  4. Bean comes to Ready state
  5. Once Spring shutdown is called @PreDestroy, destroy() and custom destroy method are called(3 methods)

Refer here

Q5.What is CGLIB in Spring?
Classes in Java are loaded dynamically at runtime. Cglib is using this feature of Java language to make it possible to add new classes to an already running Java program.Hibernate uses cglib for generation of dynamic proxies. For example, it will not return full object stored in a database but it will return an instrumented version of stored class that lazily loads values from the database on demand.Popular mocking frameworks, like Mockito, use cglib for mocking methods. The mock is an instrumented class where methods are replaced by empty implementations.

Q6.What is the difference between applicationcontext and webapplicationcontext in Spring?

  1. Spring MVC has ApplicationContext and WebApplicationContexts which is the extension of ApplicationContext
  2. There could be more than one WebApplicationContext
  3. All the Stateless attributes like DBConnections and Spring Security would be defined in ApplicationContext and shared among multiple WebApplicationContext
  4. ApplicationContext are loaded by ContextLoaderListener which is declared in web.xml
  5. A single web application can have multiple WebApplicationContext and each Dispatcher servlet (which is the front controller of Spring MVC architecture) is associated with a WebApplicationContext. The webApplicationContext configuration file *-servlet.xml is specific to a DispatcherServlet. And since a web application can have more than one dispatcher servlet configured to serve multiple requests, there can be more than one webApplicationContext file per web application.

Refer here

Q7.What are different bean scopes with realtime example?
Singleton: It returns a single bean instance per Spring IoC container.This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object. If no bean scope is specified in the configuration file, singleton is default. Real world example: connection to a database

Prototype: It returns a new bean instance each time it is requested. It does not store any cache version like singleton. Real world example: declare configured form elements (a textbox configured to validate names, e-mail addresses for example) and get “living” instances of them for every form being created.Batch processing of data involves prototype scope beans.

Request: It returns a single bean instance per HTTP request. Real world example: information that should only be valid on one page like the result of a search or the confirmation of an order. The bean will be valid until the page is reloaded.

Session: It returns a single bean instance per HTTP session (User level session). Real world example: to hold authentication information getting invalidated when the session is closed (by timeout or logout). You can store other user information that you don’t want to reload with every request here as well.

GlobalSession: It returns a single bean instance per global HTTP session. It is only valid in the context of a web-aware Spring ApplicationContext (Application level session). It is similar to the Session scope and really only makes sense in the context of portlet-based web applications. The portlet specification defines the notion of a global Session that is shared among all of the various portlets that make up a single portlet web application. Beans defined at the global session scope are bound to the lifetime of the global portlet Session.

Q8.What is Portlet application?what is the difference between a portlet and a servlet?
Servlets and Portlets are web based components which use Java for their implementation.Portlets are managed by a portlet container just like servlet is managed by servlet container.
When your application works in Portlet container it is built of some amount of portlets. Each portlet has its own session, but if your want to store variables global for all portlets in your application than you should store them in globalSession. This scope doesn’t have any special effect different from session scope in Servlet based applications.

The simplest way to think of this is that a servlet renders an entire web page, and a portlet renders a specific rectangular part (subsection) of a web page. For example, the advertising bar on the right hand side of a news page could be rendered as a portlet. But you wouldn’t implement a single edit field as a portlet, because that’s too granular. Basically if you break down a web page into it’s major sectional areas, those are good candidates to make into portlets. Portlet never renders complete web page with html start and end tags but part of page.

Spring Bean life Cycle is hooked to the below 4 interfaces Methods

  1. InitializingBean and DisposableBean callback interfaces
  2. *Aware interfaces for specific behavior
  3. Custom init() and destroy() methods in bean configuration file
  4. @PostConstruct and @PreDestroy annotations

null

InitializingBean and DisposableBean callback interfaces
InitializingBean and DisposableBean are two marker interfaces, a useful way for Spring to perform certain actions upon bean initialization and destruction.

  1. For bean implemented InitializingBean, it will run afterPropertiesSet() after all bean properties have been set.
  2. For bean implemented DisposableBean, it will run destroy() after Spring container is released the bean.

Refer Here and here

Custom init() and destroy() methods in bean configuration file
Using init-method and destroy-method as attribute in bean configuration file for bean to perform certain actions upon initialization and destruction.

@PostConstruct and @PreDestroy annotations
We can manage lifecycle of a bean by using method-level annotations @PostConstruct and @PreDestroy.

The @PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.

The @PreDestroy annotation is used on methods as a callback notification to signal that the instance is in the process of being removed by the container.

@PostConstruct vs init-method vs afterPropertiesSet
There is any difference but there are priorities in the way they work. @PostConstruct, init-method.@PostConstruct is a JSR-250 annotation while init-method is Spring’s way of having an initializing method.If you have a @PostConstruct method, this will be called first before the initializing methods are called. If your bean implements InitializingBean and overrides afterPropertiesSet, first @PostConstruct is called, then the afterPropertiesSet and then init-method.

@Component
public class MyComponent implements InitializingBean {
	
	@Value("${mycomponent.value:Magic}")
	public String value;
	
	public MyComponent() {
		log.info("MyComponent in constructor: [{}]", value); // (0) displays: Null [properties not set yet]
	}
	
	@PostConstruct
	public void postConstruct() {
		log.info("MyComponent in postConstruct: [{}]", value); // (1) displays: Magic
	}

	@Override // (equivalent to init-method in XML; overrides InitializingBean.afterPropertiesSet()
	public void afterPropertiesSet() {
		log.info("MyComponent in afterPropertiesSet: [{}]", value);  // (2) displays: Magic
	}	

        public void initIt() throws Exception {
	  log.info("MyComponent in init: " + value);
	}

	@PreDestroy
	public void preDestroy() {
		log.info("MyComponent in preDestroy: [{}], self=[{}]", value); // (3) displays: 
	}

        public void cleanUp() throws Exception {
	  log.info("Spring Container is destroy! Customer clean up");
	}
}

Spring.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
	<bean id="customerService" class="com.mkyong.customer.services.CustomerService" 
		init-method="initIt" destroy-method="cleanUp">   		
		<property name="message" value="i'm property message" />
	</bean>		
</beans>

Output

MyComponent in constructor: [null]
MyComponent in postConstruct: [Magic]
MyComponent in init: [Magic from XML]
MyComponent in afterPropertiesSet: [Magic]
MyComponent in preDestroy: [Magic]
Spring Container is destroy! Customer clean up

When to use what?
init-method and destroy-method is the recommended approach because of no direct dependency to Spring Framework and we can create our own methods.
InitializingBean and DisposableBean To interact with the container’s management of the bean lifecycle, you can implement the Spring InitializingBean and DisposableBean interfaces. The container calls afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform certain actions upon initialization and destruction of your beans.
@PostConstruct and @PreDestroy – The JSR-250 @PostConstruct and @PreDestroy annotations are generally considered best practice for receiving lifecycle callbacks in a modern Spring application. Using these annotations means that your beans are not coupled to Spring specific interfaces.

What are different ways to create Bean in Spring Boot?

  1. Using @Component over class – To create app specific bean
  2. Using @Configuration over class and @Bean over method – To create bean from third party class added as JAR dependency. You cannot add component in added JAR class files.

What is Dependency Injection?
Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself.

What are Types of Dependency Injection?

  1. Constructor Injection – Dependency provided as parameter to constructor. This ensures Object is fully initialized upon creation and promoting immutability
  2. Setter Injection – Setter injection is having independent setter for each class attributes and calling setter method while initializing. Setter Injection allow more flexibility by allowing dependencies to be set or changed after object creation.
  3. Field Injection – Field injection is old method of injecting dependencies by specifying the @Autowired over field name. It works based on Java reflection and it is not recommended as it makes code more difficult to test

What are Stereotype Annotations?

Stereotype – idea of a particular type of person or thing.

Spring comes with 4 Stereotype annotations as below.

@Component is a generic stereotype for any Spring-managed component. @Repository, @Service, @Controller are specializations of @Component for more specific use cases (in the persistence, service, and presentation layers, respectively).

  1. @Component general-purpose stereotype annotation indicating that the class is a spring component.
  2. @Controller @Controller annotation indicates that a particular class serves the role of a controller. The dispatcher scans the classes annotated with @Controller and detects methods annotated with @RequestMapping annotations within them. We can use @RequestMapping on/in only those methods whose classes are annotated with @Controller
  3. @Repository
  4. stereotype for persistence layer. @Repository’s job is to catch platform specific exceptions and re-throw them as one of Spring’s unified unchecked exception. By masking the platform specific exception to spring unified exception it helps 1.Providing higher level of Abstraction for User 2.By throwing unchecked exception it prevents user from adding unnecessary boiler plate for exception handling by means of try catch blocks

  5. @Service – @Service beans hold the business logic and call methods in the repository layer.

Note : Spring may add special functionalities for @Service, @Controller and @Repository based on their layering conventions.

How it is internally is all 3 are marked with @Component.@CompnentScan only scans @Component and does not look for @Controller, @Service and @Repository in general. They are scanned because they themselves are annotated with @Component.

@Component
public @interface Service {
    ….
}

@Component
public @interface Repository {
    ….
}

@Component
public @interface Controller {
    …
}

What happens when more than one bean of same type is found? What would be workaround?
Application would fail to start with error message Require Single bean but N beans found.

This could be addressed in two ways

  1. Using @Qualifier annotation
  2. Using @Primary annotation

@Qualifier annotation takes bean Id as value to uniquely identify a bean.

StudentController.java

public class StudentController{
 .
 @Autowired
 public StudentController(@Qualifier("student") Person person){
 .
 }
}

Student.java

@Component
public class Student implements Person{
.
}

@Primary annotation works by giving first preference to bean which is marked with @Primary annotation. If two beans are marked with @Primary annotation then Spring boot throws an error. If both @Primary and @Qualifier annotation is used, then @Qualifier annotation takes preference.

@Primary vs @Qualifier Which one takes precedence?
@Qualifier takes precedence over @Primary annotation.

What does @Lazy annotation do?
Unlike the bean which are marked with @Component are loaded at startup when the app start, @Lazy annotation does the bean loading only when it is needed.

This can be Configured globally as well by specifying in application.properties as below. If your application has lot of components and because of this the app takes long time to start then its better to use this.

application.properties

spring.main.lazy-initialization=true

Note: If you use @Lazy annotation along with @Restcontroller it may lead to timeout issues.

Report.java

public interface Report {
    String generateReport();
}

PDFReport.java

@Primary
@Component
public class PDFReport implements Report{
    public PDFReport() {
        System.out.println("Loaded PDFReport");
    }

    @Override
    public String generateReport() {
        return "PDF Report";
    }
}

excelReport.java

@Component
public class excelReport implements Report{
    public excelReport() {
        System.out.println("Loading Excel Report");
    }

    @Override
    public String generateReport() {
        return "Excel Report";
    }
}

textReport.java

@Component
@Lazy
public class textReport implements Report{
    public textReport() {
        System.out.println("Loading textReport Report");
    }
    @Override
    public String generateReport() {
        return "Text Report";
    }
}

GenerateReport.java

@RestController
public class GenerateReport {
    private Report report;

    public GenerateReport(@Qualifier("excelReport") Report report){
        this.report = report;
    }

    @GetMapping("/generateReport")
    public String generateReport(){
        return "Printing report in "+ report.generateReport() + " format";
    }
}

Excel Report format would be printed as @Qualifier would take precedence
Output in Browser(http://localhost:8080/generateReport)

Loading Excel Report
Loaded PDFReport

Printing report in Excel Report format

What are different Bean Scopes?
Singleton – Only one bean for Container, served same bean for every access
Prototype – New bean for every access
Request – New bean for every request
Session – Only one bean for Session
Application – Only one bean for Application
Websocket

@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

Checking Object based on Bean Scope – Singleton
excelReport bean with Singleton scope returning same bean every access
excelReport.java

@Component
public class excelReport implements Report{
.
.
}

GenerateReport.java

@RestController
public class GenerateReport {
    private Report report1;
    private Report report2;

    public GenerateReport(@Qualifier("excelReport") Report report1, @Qualifier("excelReport") Report report2){
        this.report1 = report1;
        this.report2 = report2;
    }

    @GetMapping("/checkBean")
    public String checkBean(){
        if(report1 == report2){
            return "Bean are Same";
        }else{
            return  "Bean are Different";
        }
    }
}

Output(http://localhost:8080/checkBean)

Bean are Same

Checking Object based on Bean Scope – Prototype
pdfReport bean with Prototype scope returning different bean on every access
PDFReport.java

@Primary
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PDFReport implements Report{
  .
  .
}

GenerateReport.java

@RestController
public class GenerateReport {
    private Report report1;
    private Report report2;

    public GenerateReport(Report report1, Report report2){
        this.report1 = report1;
        this.report2 = report2;
    }

    @GetMapping("/checkBean")
    public String checkBean(){
        if(report1 == report2){
            return "Bean are Same";
        }else{
            return  "Bean are Different";
        }
    }
}

Output(http://localhost:8080/checkBean)

Bean are Different

How to inject bean created using new Operator or Injecting Spring beans into non-managed objects
Objects for 3rd party JAR are created using @Configuration at class level and using @Bean at method level. This is one other way to create bean other than @Component as
we wont be able to change the source of 3rd party class files.

  1. Using @Configuration and @Bean annotation
  2. Using @Configurable refer here
  3. using AutowireCapableBeanFactory

Let take the below code

public class MyBean 
{
    @Autowired 
    private AnotherBean anotherBean;
}

MyBean obj = new MyBean();

I have a class doStuff in which the obj of MyBean created using new operator needs to be injected. To do this use AutowireCapableBeanFactory and call autowireBean method with beanFactory reference.

private @Autowired AutowireCapableBeanFactory beanFactory;

public void doStuff() {
   MyBean obj = new MyBean();
   beanFactory.autowireBean(obj);
   //obj will now have its dependencies autowired.
}

What is the Difference between @Inject and @Autowired in Spring Framework?
@Inject specified in javax.inject.Inject annotations is part of the Java CDI (Contexts and Dependency Injection) standard introduced in Java EE 6 (JSR-299). Spring has chosen to support using @Inject synonymously with their own @Autowired annotation.@Autowired is Spring’s own (legacy) annotation. @Inject is part of a new Java technology called CDI that defines a standard for dependency injection similar to Spring. In a Spring application, the two annotations work the same way as Spring has decided to support some JSR-299 annotations in addition to their own.

Use of the Following in Spring Framework?
@RequestMapping – All incoming requests are handled by the Dispatcher Servlet and it routes them through the Spring framework. When the Dispatcher Servlet receives a web request, it determines which controllers should handle the incoming request. Dispatcher Servlet initially scans all the classes that are annotated with the @Controller annotation. The dispatching process depends on the various @RequestMapping annotations declared in a controller class and its handler methods.The @RequestMapping annotation is used to map the web request onto a handler class (i.e. Controller) or a handler method and it can be used at the Method Level or the Class Level.

Example – for the URL http://localhost:8080/ProjectName/countryController/countries

@Controller
@RequestMapping(value = "/countryController")
public class CountryController {
 
 @RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
 public List getCountries() {
    // Some Business Logic
 } 
Annotations Equivalent
@GetMapping @RequestMapping(method = RequestMethod.GET)
@PostMapping @RequestMapping(method = RequestMethod.POST)
@PutMapping @RequestMapping(method = RequestMethod.PUT)
@DeleteMapping @RequestMapping(method = RequestMethod.DELETE)
@PatchMapping @RequestMapping(method = RequestMethod.PATCH)

@RequestParam – By using RequestParam we can get parameters to the method

@RequestMapping(value = "/display", method = RequestMethod.GET)
public String showEmployeeForm(@RequestParam("empId") String empId) {
        // Some Business Logic
}

@Pathvariable – @PathVariable is to obtain some placeholder from the URI
If empId and empName as parameters to the method showEmployeeForm() by using the @PathVariable annotation. For e.g.: /employee/display/101/Mux
empId = 101
empName = Mux

@Controller
@RequestMapping(value = "/employee")
public class EmployeeController {
    @RequestMapping(value = "/display/{empId}/{empName}")
    public ModelAndView showEmployeeForm(@PathVariable String empId, @PathVariable String empName) {
                // Some Business Logic
    } 
}

What is the Difference between @RequestParam vs @PathVariable?
@RequestParam annotation has following attributes

http://localhost:8080/springmvc/hello/101?param1=10¶m2=20
public String getDetails(
    @RequestParam(value="param1", required=true) String strParam1,
        @RequestParam(value="param2", required=false,  defaultValue = "John") String strParam2){
...
}

@PathVariable is always considered required and cannot be null whereas @RequestParam could be null

@RequestParam annotation can specify default values if a query parameter is not present or empty by using a default Value attribute, provided the required attribute is false. . If a corresponding path segment is missing, Spring will result in a 404 Not Found error.

defaultValue This is the default value as a fallback mechanism if request is not having the value or it is empty. i.e param1
name Name of the parameter to bind i.e param1
required Whether the parameter is mandatory or not. If it is true, failing to send that parameter will fail. i.e false
value This is an alias for the name attribute i.e param1

@PathVariable is to obtain some placeholder from the URI (Spring call it an URI Template) and @RequestParam is to obtain an parameter from the URI as well.@PathVariable annotation has only one attribute value for binding the request URI template. It is allowed to use the multiple @PathVariable annotation in the single method. But, ensure that no more than one method has the same pattern.Annotation which indicates that a method parameter should be bound to a name-value pair within a path segment. Supported for RequestMapping annotated handler methods.

localhost:8080/person/Tom;age=25;height=175 and Controller:
@GetMapping("/person/{name}")
@ResponseBody
public String person(
    @PathVariable("name") String name, 
    @MatrixVariable("age") int age,
    @MatrixVariable("height") int height) {

    // ...
}

How Spring will decide bean if there are multiple implementation of Same Instance?

In such case it would fail at start telling expected 1 bean but found n bean

We can use @Qualifier annotation where we can decide the bean to be loaded based on the beanId. beanId is always the component name with camel casing

public class GenerateReport {
    private Report report1;
    private Report report2;

    public GenerateReport(@Qualifier("excelReport") Report report1, Report report2){
        this.report1 = report1;
        this.report2 = report2;
    }
}

What BeanLife cycle methods are available?

@PostConstruct and @PreDestroy

@Component
public class excelReport implements Report{
    public excelReport() {
        System.out.println("Loading Excel Report");
    }

    @Override
    public String generateReport() {
        return "Excel Report";
    }

    @PreDestroy
    public void doCleanUpStuff(){
        System.out.println("Disposing ExcelReport....: Prints when Server Stops");
    }

    @PostConstruct
    public void doStartUpStuff(){
        System.out.println("Completed Initialization ExcelReport...: Prints when Server Starts");
    }
}

Output – When Server Starts

Completed Initialization ExcelReport...: Prints when Server Starts

Output – When Server Stops

Disposing ExcelReport....: Prints when Server Stops

What is use of @RequestBody and @ResponseBody?

  1. @RequestBody and @ResponseBody used in controller to implement smart object serialization and deserialization. They help you avoid boilerplate code by extracting the logic of message conversion and making it an aspect. Other than that they help you support multiple formats for a single REST resource without duplication of code.
  2. If you annotate a method with @ResponseBody, spring will try to convert its return value and write it to the http response automatically.
  3. If you annotate a methods parameter with @RequestBody, spring will try to convert the content of the incoming request body to your parameter object on the fly.

What is @Transactional used for?
When Spring loads your bean definitions, and has been configured to look for @Transactional annotations, it will create these proxy objects around your actual bean. These proxy objects are instances of classes that are auto-generated at runtime. The default behaviour of these proxy objects when a method is invoked is just to invoke the same method on the “target” bean (i.e. your bean).
Refere here

@Configuration – @Configuration as a replacement to the XML based configuration for configuring spring beans.So instead of an xml file we write a class and annotate that with @Configuration and define the beans in it using @Bean annotation on the methods.It is just another way of configuration Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.

Use @Configuration annotation on top of any class to declare that this class provides one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.

AppConfig.java

@Configuration
public class AppConfig {
 
    @Bean(name="demoService")
    public DemoClass service()
    {
        
    }
}

pom.xml
The following dependency should be added to pom.xml before using @configuration annotation to get the bean from the context

<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
		<version>5.0.6.RELEASE</version>
</dependency>
public class VerifySpringCoreFeature
{
    public static void main(String[] args)
    {
        ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class); 
        DemoManager  obj = (DemoManager) context.getBean("demoService"); 
        System.out.println( obj.getServiceName() );
    }
}

What if I want to ensure the beans are already loaded even before requested and fail-fast

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MySpringApp {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(MyConfiguration.class);
		ctx.refresh();
		MyBean mb1 = ctx.getBean(MyBean.class);
		MyBean mb2 = ctx.getBean(MyBean.class);
		ctx.close();
	}
}

In the above example Spring loads beans into it’s context before we have even requested it. This is to make sure all the beans are properly configured and application fail-fast if something goes wrong.

Now what will happen if we uncomment the @Configuration annotation in the above class. In this case, if we make a call to myBean() method then it will be a plain java method call and we will get a new instance of MyBean and it won’t remain singleton.

@Configurble – How to inject dependencies into objects that are not created by Spring

public class CarSalon {
    //...
    public void testDrive() {
        Car car = new Car();
        car.startCar();
    }
}
 
@Component
public class Car {
    @Autowired
    private Engine engine;
    @Autowired
    private Transmission transmission;
 
    public void startCar() {
        transmission.setGear(1);
        engine.engineOn();
        System.out.println("Car started");
    }
}
 
@Component
public class Engine {
//...
}
 
@Component
public class Transmission {
//...
}

In the above example

  1. We try to create a Object for Car class using new operator
  2. How ever objects created using new operator are not container managed rather Java Runtime Managed
  3. Trying to access the startCar method using car object will throw NullPointerException
  4. However using @Configurable annotation will tell Spring to inject dependencies into the object before the constructor is run
  5. You need to have these JAR files in pom.xml inorder to make it work.aspectj-x.x.x.jar, aspectjrt.jar, aspectjveawer-x.x.x.jar
@Configurable(preConstruction = true)
@Component
public class Car {
 
    @Autowired
    private Engine engine;
    @Autowired
    private Transmission transmission;
 
    public void startCar() {
        transmission.setGear(1);
        engine.engineOn();
 
        System.out.println("Car started");
    }
}

Q1.What is use of @SpringBootApplication

 @SpringBootApplication =  @Configuration + @EnableAutoConfiguration + @ComponentScan

@Configuration – Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.Refer here

@EnableAutoConfiguration – @EnableAutoConfiguration automatically configures the Spring application based on its included jar files, it sets up defaults or helper based on dependencies in pom.xml. Auto-configuration is usually applied based on the classpath and the defined beans. Therefore, we donot need to define any of the DataSource, EntityManagerFactory, TransactionManager etc and magically based on the classpath, Spring Boot automatically creates proper beans and registers them for us. For example when there is a tomcat-embedded.jar on your classpath you likely need a TomcatEmbeddedServletContainerFactory (unless you have defined your own EmbeddedServletContainerFactory bean).

@EnableAutoConfiguration has a exclude attribute to disable an auto-configuration explicitly otherwise we can simply exclude it from the pom.xml, for example if we do not want Spring to configure the tomcat then exclude spring-bootstarter-tomcat from spring-boot-starter-web.
@ComponentScan – @ComponentScan provides scope for spring component scan, it simply goes though the provided base package and picks up dependencies required by @Bean or @Autowired etc, In a typical Spring application, @ComponentScan is used in a configuration classes, the ones annotated with @Configuration. Configuration classes contains methods annotated with @Bean. These @Bean annotated methods generate beans managed by Spring container. Those beans will be auto-detected by @ComponentScan annotation. There are some annotations which make beans auto-detectable like @Repository , @Service, @Controller, @Configuration, @Component. In below code Spring starts scanning from the package including BeanA class

@Configuration
@ComponentScan(basePackageClasses = BeanA.class)
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class Config {

  @Bean
  public BeanA beanA(){
    return new BeanA();
  }

  @Bean
  public BeanB beanB{
    return new BeanB();
  }

}

Q2.What @Configurable annotation Does?
@Configurable – @Configurable is an annotation that injects dependencies into objects, that are not managed by Spring using aspectj libraries. You still use old way of instantiation with plain new operator to create objects but the spring will take care of injecting the dependencies into that object automatically for you.
Refer here

Q3.What is Starter Project?What are the Starter Project offered?
Starter POMs are a set of convenient dependency descriptors that you can include in your application
spring-boot-starter-web-services – SOAP Web Services
spring-boot-starter-web – Web & RESTful applications
spring-boot-starter-test – Unit testing and Integration Testing
spring-boot-starter-jdbc – Traditional JDBC
spring-boot-starter-hateoas – Add HATEOAS features to your services
spring-boot-starter-security – Authentication and Authorization using Spring Security
spring-boot-starter-data-jpa – Spring Data JPA with Hibernate
spring-boot-starter-data-rest – Expose Simple REST Services using Spring Data REST

Q4.What SpringApplication.run() method does?

@SpringBootApplication
public class EmployeeManagementApplication 
{
 public static void main(String[] args) 
 {
  SpringApplication.run(EmployeeManagementApplication.class, args);
 }
}

– SpringApplication class is used to bootstrap and launch a Spring application from a Java main method.
– Creates the ApplicationContext from the classpath, scan the configuration classes and launch the application
– You can find the list of beans loaded by changing the code as below.Spring Boot provides auto-configuration, there are a lot of beans getting configured by it.

  
@SpringBootApplication(scanBasePackages = "com.mugil.org.beans")
public class EmployeeManagementApplication
{
	public static void main(String[] args)
	{
		ApplicationContext ctx = SpringApplication.run(EmployeeManagementApplication.class, args);
		String[] beans = ctx.getBeanDefinitionNames();
		for(String s : beans) System.out.println(s);
	}
}

@Component
public class Employee 
{
.
.
.
}

In the console you could see employeeManagementApplication and employee getting printed with their starting
letter in lower case.

Q5.Why Spring Boot created?
There was lot of difficulty to setup Hibernate Datasource, Entity Manager, Session Factory, and Transaction Management. It takes a lot of time for a developer to set up a basic project using Spring with minimum functionality. Spring Boot does all of those using AutoConfiguration and will take care of all the internal dependencies that your application needs — all you need to do is run your application. It follows “Opinionated Defaults Configuration” Approach to reduce Developer effort.Spring Boot looks at a) Frameworks available on the CLASSPATH b) Existing configuration for the application. Based on these, Spring Boot provides the basic configuration needed to configure the application with these frameworks. This is called Auto Configuration.

Q6.
Q7.

Spring Version 4

  1. Spring Framework 4.0 provides support for several Java 8 features
  2. Java EE version 6 or above with the JPA 2.0 and Servlet 3.0 specifications
  3. Groovy Bean Definition DSL- external bean configuration using a Groovy DSL
  4. Core Container Improvements
    1. The @Lazy annotation can now be used on injection points, as well as on @Bean definitions.
    2. The @Description annotation has been introduced for developers using Java-based configuration
    3. Using generics as autowiring qualifiers
    4. Beans can now be ordered when they are autowired into lists and arrays. Both the @Order annotation and Ordered interface are supported.
    5. A generalized model for conditionally filtering beans has been added via the @Conditional annotation

Spring Version 5

  1. Functional programming with Kotlin
  2. Reactive Programming Model.The Reactive Streams API is officially part of Java 9. In Java 8, you will need to include a dependency for the Reactive Streams API specification.
  3. @Nullable and @NotNull annotations will explicitly mark nullable arguments and return values. This enables dealing null values at compile time rather than throwing NullPointerExceptions at runtime.
  4. Spring Framework 5.0 now supports candidate component index as an alternative to classpath scanning..Reading entities from the index rather than scanning the classpath.Loading the component index is cheap. Therefore the startup time with the index remains constant as the number of classes increase. While for a compoent scan the startup time increases significantly.
  5. requires Java 8 as a minimum JDK version.Spring 5 is fully compatible with Java 9.
  6. Servlet 3.1,JMS 2.0,JPA 2.1,Hibernate5,JAX-RS 2.0,Bean Validation 1.1,JUnit 5

To customize request parameter data binding, we can use @InitBinder annotated methods within our controller.

  1. The @InitBinder annotated methods will get called on each HTTP request if we don’t specify the ‘value’ element of this annotation.
  2. Each time this method is called a new instance of WebDataBinder is passed to it.
  3. To be more specific about which objects our InitBinder method applies to, we can supply ‘value’ element of the annotation @InitBinder. The ‘value’ element is a single or multiple names of command/form attributes and/or request parameters that this init-binder method is supposed to apply to.
    @InitBinder("User")
    public void customizeBinding (WebDataBinder binder) 
    {
      .
      .
      .
    }

@Controller
@RequestMapping("/register")
public class UserRegistrationController 
{
    @InitBinder("user")
    public void customizeBinding (WebDataBinder binder) 
    {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        dateFormatter.setLenient(false);
        binder.registerCustomEditor(Date.class, "dateOfBirth", new CustomDateEditor(dateFormatter, true));
    }
    
    .
    . 
}

simpleDateFormat.setLenient(false); — Will check for out of range Date. For Example, If lenient is set to true, Aug 32 will be converted to Sep 1 .