August 01, 2021

Spring Boot question and explanations

 Question: What is diff BeanFactory and ApplicationContextFactory?

Solution:

The Spring Framework comes with two IOC containers – BeanFactory and ApplicationContext. The BeanFactory(Lazy Loading is the most basic version of IOC containers, and the ApplicationContext ( Eager Loading) extends the features of BeanFactory.BeanFactory loads beans on-demand, while ApplicationContext loads all beans at startup. 

Ex:  

Resource res = new ClassPathResource("ioc-container-difference-example.xml"); BeanFactory factory = new XmlBeanFactory(res); 

Student student = (Student) factory.getBean("student");

Or 

ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml");

Reference: https://www.baeldung.com/spring-beanfactory-vs-applicationcontext

 

Question: What Is Spring Security?

Solution:

Spring Security is a separate module of the Spring framework that focuses on providing authentication and authorization methods in Java applications. It also takes care of most of the common security vulnerabilities such as CSRF attacks.

To use Spring Security in web applications, we can get started with the simple annotation @EnableWebSecurity.

For more information, we have a whole series of articles related to security.

Question: Name Some of the Design Patterns Used in the Spring Framework?

Solution:

  • Singleton Pattern – singleton-scoped beans
  • Factory Pattern – Bean Factory classes
  • Prototype Pattern – prototype-scoped beans
  • Adapter Pattern – Spring Web and Spring MVC
  • Proxy Pattern – Spring Aspect-Oriented Programming support
  • Template Method Pattern – JdbcTemplateHibernateTemplate, etc.
  • Front Controller – Spring MVC DispatcherServlet
  • Data Access Object – Spring DAO support
  • Model View Controller – Spring MVC

Reference: https://www.baeldung.com/spring-interview-questions

 

Question: Spring WebFlux?

Solution:

The original web framework included in the Spring Framework, Spring Web MVC, was purpose-built for the Servlet API and Servlet containers. The reactive-stack web framework, Spring WebFlux, was added later in version 5.0. It is fully non-blocking, supports Reactive Streams back pressure, and runs on such servers as Netty, Undertow, and Servlet 3.1+ containers.

Reference: https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux



Question: Spring REST – HTTP OPTIONS Request Handler Example

Solution:

HTTP OPTIONS Method

The HTTP OPTIONS method is used to describe the communication options for the target resource. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

  • If the Request-URI is an asterisk (“*”), the OPTIONS request is intended to apply to the server in general rather than to a specific resource.
  • If the Request-URI is not an asterisk, the OPTIONS request applies only to the options that are available when communicating with that resource.
  • Responses to this method are not cacheable.


@RequestMapping(value="/buckets", method = RequestMethod.OPTIONS)

    ResponseEntity<?> collectionOptions() 

    {

         returnResponseEntity

                 .ok()

                 .allow(HttpMethod.GET, HttpMethod.POST, HttpMethod.OPTIONS)

                 .build();

    }

 

Reference: https://howtodoinjava.com/spring-rest/http-options-request-handler/


Question: Spring – Inversion of Control vs Dependency Injection

Solution:

What is Inversion of Control (IoC)

In traditional programming, the flow of the business logic is determined by objects that are statically assigned to one another. With inversion of control, the flow depends on the object graph that is instantiated by the assembler and is made possible by object interactions being defined through abstractions. The binding process is achieved through dependency injection, although some argue that the use of a service locator also provides inversion of control.

Inversion of control as a design guideline serves the following purposes:

  1. There is a decoupling of the execution of a certain task from implementation.
  2. Every module can focus on what it is designed for.
  3. Modules make no assumptions about what other systems do but rely on their contracts.
  4. Replacing modules has no side effect on other modules.

What is Dependency Injection (DI)

IoC is a design paradigm with the goal of giving more control to the targeted components of your application, the ones getting the work done. While Dependency injection is a pattern used to create instances of objects that other objects rely on without knowing at compile time which class will be used to provide that functionality. IoC relies on dependency injection because a mechanism is needed in order to activate the components providing the specific functionality.

How to implement IoC

In object-oriented programming, there are several basic techniques to implement inversion of control. These are:

  1. using a factory pattern
  2. using a service locator pattern
  3. using a dependency injection of any given below type:
    • a constructor injection
    • a setter injection
    • an interface injection

Inversion of control in Spring

The org.springframework.beans and org.springframework.context packages provide the basis for the Spring Framework’s IoC container. The BeanFactory interface provides an advanced configuration mechanism capable of managing objects of any nature. The ApplicationContext interface builds on top of the BeanFactory (it is a sub-interface) and adds other functionality such as easier integration with Spring’s AOP features, message resource handling (for use in internationalization), event propagation, and application-layer specific contexts such as the WebApplicationContext for use in we

Reference: https://stackoverflow.com/questions/3715967/when-should-we-call-system-exit-in-java


Question: What  is System.exit()?

Solution:

The java.lang.System.exit() method exits current program by terminating running Java virtual machine. This method takes a status code. A non-zero value of status code is generally used to indicate abnormal termination. This is similar exit in C/C++.

Following is the declaration for java.lang.System.exit() method:

public static void exit(int status)

exit(0) : Generally used to indicate successful termination.
exit(1) or exit(-1) or any other non-zero value – Generally indicates unsuccessful termination.


Additional info:

System.exit(0);

System.out.println("This line will never be reached");


System.exit(0) terminates the JVM. The parameter is passed back to the OS and is normally used to indicate abnormal termination (eg some kind of fatal error), so if you called java from a batch file or shell script you'd be able to get this value and get an idea if the application was successful.

System.exit(42)  == A script that called the application. Works in Windows, Unix and all other scriptable environments.


Reference: https://www.geeksforgeeks.org/system-exit-in-java/


Question: What is spring bean lifecycle?

Solution:


Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed

  

Reference: https://www.geeksforgeeks.org/bean-life-cycle-in-java-spring/

https://reflectoring.io/spring-bean-lifecycle/


Question: Error Handling for REST with Spring  or Spring Boot @ControllerAdvice

Solution:

There are couple of ways to handle exception in springbok

Solution 1: the Controller-Level @ExceptionHandler

Solution 2: the HandlerExceptionResolver

Solution 3: @ControllerAdvice

Solution 4: ResponseStatusException (Spring 5 and Above)

Handle the Access Denied in Spring Security


Default Spring Boot Support exception messages:

In a nutshell, it serves a fallback error page for browsers (a.k.a. the Whitelabel Error Page) and a JSON response for RESTful, non-HTML requests:

{

    "timestamp": "2019-01-17T16:12:45.977+0000",

    "status": 500,

    "error": "Internal Server Error",

    "message": "Error processing the request!",

    "path": "/my-endpoint-with-exceptions"

}


Using @ControllerAdvice:

  • SpringBoot @ControllerAdvice tutorial shows how to use @ControllerAdvice annotation to manage exceptions in a Spring Boot application.
  • @ControllerAdvice is a specialization of the @Component annotation which allows to handle exceptions across the whole application in one global handling component. It can be viewed as an interceptor of exceptions thrown by methods annotated with @RequestMapping and similar.
  • ResponseEntityExceptionHandler is a convenient base class for @ControllerAdvice classes that wish to provide centralized exception handling across all @RequestMapping methods through @ExceptionHandler methods. It provides an methods for handling internal Spring MVC exceptions. It returns a ResponseEntity in contrast to DefaultHandlerExceptionResolver which returns a ModelAndView.


Using the Controller-Level @ExceptionHandler:

The first solution works at the @Controller level. We will define a method to handle exceptions and annotate that with @ExceptionHandler:

public class FooController{

    //...

    @ExceptionHandler({ CustomException1.class, CustomException2.class })

    public void handleException() {

        //

    }

}

Reference: https://zetcode.com/springboot/controlleradvice/

https://www.baeldung.com/exception-handling-for-rest-with-spring


1 comment:

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts