Posts

Showing posts from April, 2018

Dependency Injection and Inversion of Control

dependency-injection-and-inversion-of-control We often mix the Dependency Injection (DI) with the Inversion of Control (IoC). In fact, DI is one form of IoC. This article clarifies the terms. Dependency Injection (DI) Classes that employ dependency injection specify the objects that they interact with through constructor, interface, or setters. Inversion of Control (IoC) Object location or instantiation is removed as a responsibility for a caller class and instead left to a container that manages this tier of logic. The control of objects instantiation is inverted from the object caller class to the container. Relationship Dependency Injection is one form of the broader technique of Inversion of Control. The client delegates the responsibility of providing its dependencies to external code (the injector). The client is not allowed to call the injector code. It is the injecting code that constructs the services and calls the client to inject them. The client

Spring Data Substitutes ObjectMapper

spring-data-substitutes-objectmapper Most of the times when we need a DTO mapping from our persistent entity, we would think of using an ObjectMapper. However, with the help of the Spring Data, you might not need an ObjectMapper. This lesson presents a solution to use Spring Data to replace simple ObjectMapper use case. Story Given a Book class and one of it’s DTO class BookMeta as shown below, create a repository method that retrieve all BookMeta by category. @Entity public class Book { private String title ; private String author ; private String category ; private String intro ; // getter and setters are ommitted for brevity } @Entity public class BookMeta { private String title ; private String author ; public BookMeta ( String title , String author ) { this . title = title ; this . author = author ; } // getter and setters are ommitted for brevity } Solution As part of JPA, JPQL now suppo

Java Servlet CORS Filter with Preflight Options

java-servlet-cors-filter-with-preflight-options A CORS filter determines what types of access control header will be set for the server response to the client’s request. However, when the resource being accessed is behind a security layer, in order to send the payload to the security filters, an optional request by browsers is sent to the server before the actual request. This lesson presents one implementation of a CORS filter that supports preflight options request. Story The following code is an implementation of a CORS filter that just works fine without a security layer. public class SimpleCorsFilter implements Filter { @Override public void init ( final FilterConfig filterConfig ) throws ServletException { } @Override public void doFilter ( final ServletRequest request , final ServletResponse response , final FilterChain chain ) throws IOException , ServletException { HttpServletResponse resp = ( Ht