GET

  1. GET is idempotent and can be requested any number of times
  2. GET requests can be cached, can be distributed & shared
  3. GET request is less secured compared to POST.

POST

  1. Used to Create a resource
  2. Post is not idempotent.x++ is not idempotent
  3. POST is NOT idempotent. So if you retry the request N times, you will end up having N resources with N different URIs created on server.

PUT

  1. Used to Create or Modify a resource
  2. PUT is idempotent, so if you PUT an object twice, it has no effect.
  3. x=5 is idempotent.You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)!

When to use Put and Post
You can use both PUT or POST for creating the resource until the client decides the resource location in the Server.But if the server decides the resource location using

POST /questions/ HTTP/1.1
Host: www.example.com/

Note that the following is an error:

POST /questions/ HTTP/1.1
Host: www.example.com/

If the URL is not yet created, you should not be using POST to create it while specifying the name. This should result in a ‘resource not found’ error because does not exist yet. You should PUT the resource on the server first.

You could though do something like this to create a resources using POST:

POST /questions HTTP/1.1
Host: www.example.com/

Note that in this case the resource name is not specified, the new objects URL path would be returned to you.

PUT is Used to create a resource, or overwrite it. While you specify the resources new URL.

PUT /questions/ HTTP/1.1
Host: www.example.com/

To overwrite an existing resource:

PUT /questions/ HTTP/1.1
Host: www.example.com/

PATCH
Patch request says that we would only send the data that we need to modify without modifying or effecting other parts of the data. Ex: if we need to update only the first name, we pass only the first name.PATCH – HTTP.PATCH can be used when the client is sending one or more changes to be applied by the server. The PATCH method requests that a set of changes described in the request entity be applied to the resource identified by the Request-URI. The set of changes is represented in a format called a patch document.

In PUT request, the enclosed entity would be considered as the modified version of a resource which residing on server and it would be replaced by this modified entity.

In PATCH request, enclosed entity contains the set of instructions that how the entity which residing on server, would be modified to produce a newer version.

DELETE

DELETE is pretty easy to understand. It is used to delete a resource identified by a URI.On successful deletion, return HTTP status 200 (OK) along with a response body, perhaps the representation of the deleted item (often demands too much bandwidth), or a wrapped response (see Return Values below). Either that or return HTTP status 204 (NO CONTENT) with no response body. In other words, a 204 status with no body, or the JSEND-style response and HTTP status 200 are the recommended responses.

  1. Caching is the ability to store copies of frequently accessed data in several places along the request-response path. When a consumer requests a resource representation, the request goes through a cache or a series of caches (local cache, proxy cache or reverse proxy) toward the service hosting the resource.
  2. If any of the caches along the request path has a fresh copy of the requested representation, it uses that copy to satisfy the request. If none of the caches can satisfy the request, the request travels all the way to the service (or origin server as it is formally known).
  3. Using HTTP headers, an origin server indicates whether a response can be cached and if so, by whom, and for how long. Caches along the response path can take a copy of a response, but only if the caching metadata allows them to do so.
  4. Few are the advantages of Caching
    • Reduce bandwidth
    • Reduce latency
    • Reduce load on servers
    • Hide network failures
  5. GET requests are cachable by default – until special condition arises. Usually, browsers treat all GET requests cacheable.
  6. POST requests are not cacheable by default but can be made cacheable if either an Expires header or a Cache-Control header with a directive, to explicitly allows caching, is added to the response. Responses to PUT and DELETE requests are not cacheable at all.

There are two main HTTP response headers that we can use to control caching behavior:
Expires : The Expires HTTP header specifies an absolute expiry time for a cached representation. Beyond that time, a cached representation is considered stale and must be re-validated with the origin server. To indicate that a representation never expires, a service can include a time up to one year in the future.

Expires: Wed, 6 March 2019 15:09:49 IST

Cache-Control:
The header value comprises one or more comma-separated directives. These directives determine whether a response is cacheable, and if so, by whom, and for how long e.g. max-age or s-maxage directives.

Cache-Control: max-age=3600
ETag: "abcd1234567n34jv"
(or)
Last-Modified: Fri, 10 May 2016 09:17:49 IST

Cacheable responses (whether to a GET or to a POST request) should also include a validator — either an ETag or a Last-Modified header.

ETag
An ETag value is an opaque string token that a server associates with a resource to uniquely identify the state of the resource over its lifetime. When the resource changes, the ETag changes accordingly.

Last-Modified
Whereas a response’s Date header indicates when the response was generated, the Last-Modified header indicates when the associated resource last changed. The Last-Modified value cannot be later than the Date value.

Supplier Accounts.java

@FunctionalInterface
public interface Accounts{
  abstract String showAccountType(); 
}

AccountImpl.java

public class AccountImpl {
 public static void main(String[] args) {
  //Implementation of Custom Supplier Method for Accounts Interface 
  Accounts squareRoot = () -> "Hi there";
  System.out.println(squareRoot.showAccountType());
 }
}

The above code could be expanded as below using Anonymous Inner Class

public class AccountImpl {
 public static void main(String[] args) {
  Accounts squareRoot = new Accounts() {
   @Override
   public String showAccountType() {
    return "Hi there";
   }
  };
  System.out.println(squareRoot.showAccountType());
 }
}
Consumer Accounts.java

@FunctionalInterface
public interface Accounts {
 abstract void showAccountType(String strAccType);
}

AccountImpl.java

public class AccountImpl {
 public static void main(String[] args) {
  //Implementation of Custom Consumer Method for Accounts Interface
  Accounts squareRoot = (strAccType) -> System.out.println(strAccType);
  squareRoot.showAccountType("Savings");
 }
}

The above code could be expanded as below using Anonymous Inner Class

public class AccountImpl {
 public static void main(String[] args) {
  Accounts squareRoot = new Accounts() {
   @Override
   public void showAccountType(String strAccType) {
    System.out.println(strAccType);
   }
  };
 }
}
Predicate Accounts.java

@FunctionalInterface
public interface Accounts{
  abstract boolean showAccountType(String accountType);
}

AccountImpl.java

public class AccountImpl {
 public static void main(String[] args) {
  //Implementation of Custom Predicate Method for Accounts Interface
  Accounts squareRoot = (accountType) -> {
   if ("Savings" == accountType)
    return true;
   else
    return false;
  };

  if (squareRoot.showAccountType("Savings"))
   System.out.println("Savings");
  else
   System.out.println("Invalid Account");
 }
}

The above code could be expanded as below using Anonymous Inner Class

public class AccountImpl {
 public static void main(String[] args) {
  Accounts squareRoot = new Accounts() {
   @Override
   public boolean showAccountType(String accountType) {
    if ("Savings" == accountType)
     return true;
    else
     return false;
   }
  };

  if (squareRoot.showAccountType("Savings"))
   System.out.println("Savings");
  else
   System.out.println("Invalid Account");   
 }
}
Function Accounts.java

@FunctionalInterface
public interface Accounts  
{
 abstract String showAccountType(String accountType, String returnAccType);
}

AccountImpl.java

public class AccountImpl {
 public static void main(String[] args) {
  //Implementation of Custom Function Method for Accounts Interface
  Accounts squareRoot = (accountType, returnType) -> {
   if (accountType == "Savings")
    return "Credit";
   else
    return "Debit";
  };

  System.out.println(squareRoot.showAccountType("Savings", null));
 }
}

The above code could be expanded as below using Anonymous Inner Class

public class AccountImpl {
 public static void main(String[] args) {
  Accounts squareRoot = new Accounts() {
   @Override
   public String showAccountType(String accountType, String returnAccType) {

    if (accountType == "Savings")
     return "Credit";
    else
     return "Debit";
   }
  };

  System.out.println(squareRoot.showAccountType("Savings", null));
 }
}
Urnary Operator Accounts.java

@FunctionalInterface
public interface Accounts{
 abstract String showAccountType(String accountType);
}

AccountImpl.java

public class AccountImpl {
 public static void main(String[] args) {
  //Implementation of Custom Operator Method for Accounts Interface
  Accounts squareRoot = (accountType) -> {
   return "AccountType is " + accountType;
  };
  squareRoot.showAccountType("Savings");
 }
}

The above code could be expanded as below using Anonymous Inner Class

public class AccountImpl {
 public static void main(String[] args) {
  Accounts squareRoot = new Accounts() {
   @Override
   public String showAccountType(String accountType) {
    return "AccountType is " + accountType;
   }
  };

  System.out.println(squareRoot.showAccountType("Savings"));
 }
}
  1. Optional is a wrapper class which makes a field optional which means it may or may not have values.
  2. ptional as a single-value container that either contains a value or doesn’t (it is then said to be “empty”)
  3. The advantage compared to null references is that the Optional class forces you to think about the case when the value is not present. As a consequence, you can prevent unintended null pointer exceptions.
  4. The intention of the Optional class is not to replace every single null reference. Instead, its purpose is to help design more-comprehensible APIs so that by just reading the signature of a method, you can tell whether you can expect an optional value. This forces you to actively unwrap an Optional to deal with the absence of a value.

Lets take the below code

String version = computer.getSoundcard().getUSB().getVersion();

In the above piece of java code if any of the 3 values other the Version is NULL will throw a null pointer exception. To prevent this lets add a null check

String version = "UNKNOWN";
if(computer != null){
  Soundcard soundcard = computer.getSoundcard();
  if(soundcard != null){
    USB usb = soundcard.getUSB();
    if(usb != null){
      version = usb.getVersion();
    }
  }
}

Now the above code has become Clumsy with less readability and lot of boilerplate code has been added.
In languages like Groovy these conditions could be handles like one below

String version = computer?.getSoundcard()?.getUSB()?.getVersion();
(or)
String version = 
    computer?.getSoundcard()?.getUSB()?.getVersion() ?: "UNKNOWN";

Now lets replace the above code with new Optional in Java 8

public class Computer {
  private Optional<Soundcard> soundcard;  
  public Optional<Soundcard> getSoundcard() { ... }
  ...
}

public class Soundcard {
  private Optional<USB> usb;
  public Optional<USB> getUSB() { ... }

}

public class USB{
  public String getVersion(){ ... }
}

The advantage compared to null references is that the Optional class forces you to think about the case when the value is not present. As a consequence, you can prevent unintended null pointer exceptions.

What is the Point of Optional when the same could be done using NULL Check?
If you are doing NULL check the traditional way there would be no much difference. However, the difference is felt when you are carrying out chaining operations in streams and the datatypes returned are optional.The difference may not be significant in this case but as the chain of objects increases e.g. person.getAddress.getCity().getStreet().getBlock(),

Methods in Optional
get()
If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException

void ifPresent(Consumer consumer)
If a value is present, it invokes the specified consumer with the value, otherwise does nothing.

boolean isPresent()
Returns true if there is a value present, otherwise false.

static Optional ofNullable(T value)
Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.

T orElse(T other)
Returns the value if present, otherwise returns other.

T orElseGet(Supplier other)
Returns the value if present, otherwise invokes other and returns the result of that invocation.

orElseThrow(Supplier exceptionSupplier)
Returns the contained value, if present, otherwise throws an exception to be created by the provided supplier.

Lets take a simple example where Optional returns Empty or Value based on some Condition

package com.example.demo;
import java.util.Optional;
public class Test {

 public static void main(String[] args) {
  //IfPresent
  Optional < String > strOpt = getName(" Piggy");
  System.out.print("First Call -");
  strOpt.ifPresent(System.out::println);


  Optional < String > strOpt2 = getName("");
  System.out.print("Second Call -");
  strOpt2.ifPresent(System.out::println);

  System.out.println();

  //IsPresent and get
  Optional < String > strOpt3 = getNewName(" Biggy");
  System.out.print("Third Call -");

  if (strOpt3.isPresent())
   System.out.println(strOpt3.get());


  //orElse
  Optional < String > strOpt4 = getNewName(null);
  System.out.print("Fourth Call -");
  System.out.println(strOpt4.orElse(" Hippi"));


 }

 public static Optional < String > getName(String strName) {
  if (strName.length() > 0)
   return Optional.of(strName);
  else
   return Optional.empty();
 }

 public static Optional < String > getNewName(String strName) {
  //Optional strNewName = (strName!=null)?Optional.of(strName):Optional.empty();
  return Optional.ofNullable(strName);
 }
}

Output

First Call - Piggy
Second Call -
Third Call - Biggy
Fourth Call - Hippi

@RequestBody, spring will try to convert the content of the incoming request body to your parameter object on the fly.@ResponseBody, spring will try to convert its return value and write it to the http response automatically

@Controller
@RequestMapping(value = "/bookcase")
public class BookCaseController 
{ 
    private BookCase bookCase;
 
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public BookCase getBookCase() {
        return this.bookCase;
    }
 
    @RequestMapping(method = RequestMethod.PUT)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void setBookCase(@RequestBody BookCase bookCase) {
        this.bookCase = bookCase;
    } 
}

Depending on your configuration, spring has a list of HttpMessageConverters registered in the background. A HttpMessageConverters responsibility is to convert the request body to a specific class and back to the response body again, depending on a predefined mime type. Every time an issued request is hitting a @RequestBody or @ResponseBody annotation spring loops through all registered HttpMessageConverters seeking for the first that fits the given mime type and class and then uses it for the actual conversion.

Refer here

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>

Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.

3 types of method references:

  1. Reference to a static method
  2. Reference to an instance method
  3. Reference to a constructor

Reference to a static method
Syntax

  ClassName::MethodName
import java.util.function.BiFunction;
class Arithmetic 
 {
 public static int add(int a, int b) 
 {
  return a + b;
 }
}
public class MethodReference 
{
 public static void main(String[] args) 
 {
  BiFunction < Integer, Integer, Integer > adder = Arithmetic::add;
  int result = adder.apply(10, 20);
  System.out.println(result);
 }
}

Reference to an instance method
Syntax

Object::methodName
import java.util.function.BiFunction;
class Arithmetic 
 {
 public int add(int a, int b) 
 {
  return a + b;
 }
}
public class MethodReference 
{
 public static void main(String[] args) 
 {
  Arithmetic objArithmetic = new Arithmetic();
  BiFunction < Integer, Integer, Integer > adder = objArithmetic::add;
  int result = adder.apply(10, 20);
  System.out.println(result);
 }
}

Reference to a constructor
Syntax

ClassName::new  
interface Messageable {
 Message getMessage(String msg);
}
class Message {
 Message(String msg) {
  System.out.print(msg);
 }
}
public class ConstructorReference {
 public static void main(String[] args) {
  Messageable hello = Message::new;
  hello.getMessage("Hello");
 }
}

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