Introduction to Java Loops

Introduction to Java Loops

Looping through an array or a collection is a very common day to day activity, in this post, we will get an introduction to Java Loops. We will be exploring various options for looping using Java.

 

Introduction

Looping is a feature which allows us to execute through a set of statements until our condition expression evaluates to false. Java provides multiple ways to Loop and choice is dependent upon the particular use case where we want to use it.

On a high level here are the options for Java Loops.

  1. for Loop
  2. While Loop
  3. Do-While Loop
  4. Enhanced for-each Loop

 

1. for Loop

A simple for loop which allows us to iterate over items until a specified condition is met or satisfied. This normally works with the help of a counter which will be initialized at the start of the execution and will be incremented with each iteration.

Based on the Java doc definition, a simple for loop have the following syntax

for (initialization; termination;increment) {
    statement(s)
}

Here are some of the important point to keep in mind while using simply for loop

  1. initialization will be done only once at the beginning of the loop.
  2. Loop will terminate when the termination condition will be evaluated as true.
  3. The increment is evaluated/ processed at each iteration.

 

Here is a very simple example

public class ForLoops {

    public static void main(String[] args) {

        for(int i=0 ;i<=6 ; i++){

            System.out.println("Value of i =" +i);
        }
    }
  
}

Output

Value of i =0
Value of i =1
Value of i =2
Value of i =3
Value of i =4
Value of i =5
Value of i =6

All three expressions for the for loop are optional which means you can easily create an infinite loop by removing all these expressions.

public class InfiniteForLoop {

    public static void main(String[] args) {

        //infinite loop by removing all expressions
        for(; ; ){

            System.out.println("Infinite Loop");
        }
    }
}

 

2. While Loop

As the name suggests, While loop will continually process statement or given code block while it’s evaluation expression is true.Here is an expression for while loop as per Java docs.

while (expression) {
    statement(s)
}

Here is a sample programme

public class WhileLoop {

    public static void main(String[] args) {

        int i = 0;

        while (i < 3) {
            System.out.println("Value of i = " + i);
            i++;
        }
    }
}

You can implement infinite while loop by setting expression as true 

public class WhileLoop {

    public static void main(String[] args) {
        while (true) {
          //your work
        }
    }
}

 

 

3. Do-While Loop

The do-while and while loop is similar and work in a similar way except that in a do-while loop, an expression is evaluated at the bottom as compared to the while loop.To put in another way, do block are always executed at least once.

public class DoWhileLoop {

    public static void main(String[] args) {

        int i = 0;
        do {
            System.out.println("Value of i = " + i);
            i++;
        } while (i < 5);
    }
}

 

4. Enhanced for Loop

Java 5 introduced a variation of the for loop known as enhanced for-loop.It provides a simple way to iterate over the elements of array/collection.Here is a syntax for the enhanced for loop

for(Type item : items){
    //Business rules
}

In order to use this loop, we only need to define following 2 things

  1. Type to hold element being iterated.
  2. Source of the iteration

We are no longer required to declare iteration index to loop through the element as this will be taken care internally by JDK. Here is an example demonstrating difference between simple for loop and enhanced for loop in Java

public class EnhancedForLoop {

    public static void main(String[] args) {
        
        List<String> stringList= Arrays.asList("One", "Two","Three");
        
        //in old for loop
        for(int i =0 ; i<= stringList.size() ; i++){
            System.out.println("List Value is "+stringList.get(i));
        }
        
        //with enhanced for loop
        for(String value : stringList){
            System.out.println("List Value is "+value);
        }
    }
}

 

4.1 Iterable.forEach()

We are already into Java 9 and it will not be good if we do not cover new enhancement introduced in Java 8.We have now a default method named forEach() added to the java.lang.Iterable<T> interface with an ability to accept lambda expressions.

Let’s take our earlier example and see how this can be redefined by utilizing new Java 8 feature

public class ForEachJava8 {

    public static void main(String[] args) {

        List<String> stringList= Arrays.asList("One", "Two","Three", "Four");

        //Before Java 8

        for(String value : stringList){

            //work will be done here
        }

        // With Java 8 and Lambda Expressions

        stringList.forEach(name -> System.out.println(name));

    }
}

As we saw, with introduction of Lambda Expression in Java 8, we were able to iterate through element using a single line of code

stringList.forEach(name -> System.out.println(name));

I will be covering benefits of Lambda and parallel execution in some other post.Read our article Lambda Expressions in Java to start with Java 8 Lambda Expressions.

Summary

In this post, we discussed different Java Loops. We covered new enhancement introduced in Java 5 for enhanced for loop along with the new features introduced with Java 8. You can download the examples from Github

What is Spring Boot

What is Spring Boot

This will be a short post more focused towards introducing Spring Boot, We will discussWhat is Spring Boot“? and how Spring Boot is helpful in building Java based enterprise applications.

 

Introduction

As a Java developer, it’s very likely that we have worked with Spring Framework based application directly or indirectly.Spring has a number of ways to configure its behavior, it provides the option to use XML based configurations or to use Annotations, JavaConfig is becoming the de facto standard for the new Spring based applications.Although these options seem really good, with large enterprise applications involves hundreds of modules and complicated business rules, these configurations can become really complicated. Below are some of the complications which large application can bring in to the picture

 

  • Each module has its own configurations.
  • Each module contains its own set of dependencies (third-party dependencies)
  • Upgrading application (e.g Spring 4.x to 5.x) will be complicated as we need to ensure that all required dependencies are upgraded correctly.
  • In case some of the dependencies are not working correctly, trying to find out root cause is a large application is really complicated and challenging.

 

All above issues are more or less related to making sure we have everything before dev team can start working on actual tasks. Now let’s talk about another use case which we use to do with any Spring based application, Let’s say we want to create a web-based application, these are most common steps most of us will be doing on regular basis

 

  • Create a web application using Maven or IDE of our choice.
  • Copy standard web application configurations (web.xml configuration for Spring MVC application).
  • Tweak above configurations based on our requirements.
  • Configure Spring MVC standard beans like ViewResolver, MessageSource etc.
  • Configure Database properties to be used for our application.
  • Establish DB layer and ensure underlying DB connection is in place before we can start using it (EntityManagerFactory, TransactionManager etc.)

 

This list can grow significantly based on type of our application

 

 

1. What is Spring Boot

All of the above steps seem very to us but they add a lot of overhead to the development team and instead of focusing on solving the actual business problem, initial time will be consumed to ensure that everything is in the correct place to start work. Think of Spring Boot as a tool which can do these initial tasks for us automatically.Spring Boot works on an opinionated view of the Spring platform being used by us and ensures that team can quickly start working on solving the actual business problem rather than spending time on the initial configurations and setup.

Spring Boot provides the following feature out of the box

    1. It simplifies Spring dependencies by taking the opinionated view ( we will discuss it in more details).
    2. Spring Boot provides a preconfigured set of technologies/framework to reduces error-prone configuration so we as a developer focused on building our business logic rather than thinking of project setup.
    3. You really don’t need those big XML configurations for your project.
    4. Embed Tomcat, Jetty or Undertow directly.
    5. Provide opinionated Maven POM to simplify your configuration

 

Using Spring Boot, it’s easy to manage and handle issues highlighted in the introduction section. .We are not required to manually search for compatible jars during upgrade,  Spring Boot will ensure that our application is upgraded to  the correct version (This is called working on application with minimum fuss)

Let’s take a look at a sample pom.xml for our web application to get an understanding of sample Spring Boot configuration

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javadevjournal.demo</groupId>
    <artifactId>sample web application</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
    </parent>
    <name>rWeb Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-hateoas</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
</project>

Just pay close attention to <packaging> tag, Spring Boot provides flexibility to run our application as a jar and not forcing us to use war as required packaging type.

2. Better Dependency Management

Just check configuration closely and you won’t be finding any entry for all those Spring dependencies (like web MVC, core, AOP, ORM, Validation API etc.), you might have noticed similar entries spring-boot-starter-*, this is Spring Boot dependency management process. We have added spring-boot-starter-web to our pom.xml and Spring Boot will pull all required dependencies for Spring MVC application (no more manual configurations).

 

 

3. Auto Configurations

Auto Configuration is another interesting feature of Spring Boot this is why Spring Boot team say’s that it has opinions.These are some of work Spring Boot will do for you

  1. It will add all dependencies as highlighted in point 2.
  2. Auto Configurations indicates that Spring Boot has some reasonable defaults i.e based on the configurations Spring Boot will guess the type of application and will supply default implementations required to run your application in case we have not defined those in our application. in case you define these, Spring Boot will ensure that these defaults will be taken out of the context and let your custom configurations will take charge of application.
  3. To give a more clear picture, let’s say you have defined dependency for JPA and have not defined any database configurations, Spring Boot will automatically create required configurations for us. 

 

Read our article on to get the in-depth understanding of Spring Boot Auto Configurations.

 

 

3. Servlet Container

Do you recall that process of deploying your application on the Servlet container (Tomcat etc.), every time we make those small changes and require to deploy those into the app server to test our changes? Spring Boot provides support for embedded Servlet container and we are no longer require to deploy our application on app server (This can be run easily using standard main method) but at the same time we can access our application on the browser using http://<host>:<port>

Spring-boot-starter-web entry in our pom.xml will provide embedded servlet container for our web application, Apache Tomcat is the default servlet container provided by Spring Boot, however, Spring boot provides ways to use other servlet containers (all we have to add the required starter for this).

 

Read our post Building an Application with Spring Boot to start building your application with Spring Boot.

 

 

Summary

In this post, we get an understanding of the Spring Boot, we covered What is Spring Boot? and what are the Benefits of Spring Boot? We discussed different features of the Spring Boot. Spring Boot internally does a lot of things for us which seems to magical to us. In this series, we will be uncovering all these internal details of the Spring Boot.

Lambda Expressions in Java

Lambda Expressions in Java

In this post, we will be discussing  Lambda Expressions in Java, a new feature introduced in Java 8.

 

Introduction

Added in Java 8, lambda expressions enhance the Java performance by increasing the expressive power of the language.

Before getting into Java Lambda Expressions, first, we need to understand what is a functional interface.

If a Java interface that contains one and only one abstract method then it is termed as the functional interface. This only one method specifies the intended purpose of the interface. For example, the Runnable interface form package java.lang; is a functional interface because it constitutes only one method i.e. run()

Here’s how you define a functional interface:

@FunctionalInterface
public interface MyInterface{
    double getValue();
}

However, the @FunctionalInterface annotation is not necessary, but it is wise to use it because it forces the Java compiler to indicate that the Interface defined is a functional interface and it must have only one abstract method. The functional interface is sometimes referred as Single Abstract Method or SAM type.

For more information, read our post on Functional interfaces in Java.

 

1. What are Lambda Expressions

Lambda expression is, essentially, an anonymous or unnamed method. The lambda expression does not execute on its own. Instead, it is used to implement a method defined by a functional interface.There will be a natural question “How to define lambda expression in Java?” 

The lambda expression introduces a new syntax element and operator in Java language. The new operator is referred to as the lambda operator or the arrow operator. Which is ->

Let’s write a simplest lambda expression which just returns a constant double value.

() -> 3.1415

The above lambda expression syntax is equivalent to the following method:

double getPiValue() { return 3.1415; }

 

The left side of the expression specifies any parameters required by the expression, whereas the right side is the lambda body, which specifies the action of the lambda expression.

 

2. Lambda Body

The lambda body is of two types.

  1. A body with a single expression () -> System.out.println(“Lambdas are great”);
  2. A body that consists of a block of code. () -> { double pi = 3.1415; return pi; }

 

A lambda expression can also have parameters. For example: (n) -> (n%2)==0

 

This lambda expression evaluates it the value of n is even or odd.If lambda body is a code block, you must always return a value explicitly. But, if lambda body is an expression, return statement is not required. Let’s write some practical Java code with lambda expression which simply returns the value of Pi. As mentioned earlier, the lambda expression is not executed on its own. Rather, it forms the implementation of the abstract method defined by the functional interface.

 

So, first define a functional interface (MyInterface.java):

import java.lang.FunctionalInterface;

// This is functional interface
@FunctionalInterface
public interface MyInterface {
    double getPiValue();
}

Now, we assign the lambda expression to the instance of the functional interface.

public class LambdaMain {
    public static void main(String[] args) {
        // create a reference to MyInterface instance.
        MyInterface myInterface;

        // use lambda in assignment context
        myInterface = () -> 3.1415;


        // call getValue() from myInterface instance, which is implemented by the previously assigned lambda expression
        System.out.println("Value of Pi = " + myInterface.getValue());
    }
}

When you run the program, the output will be:

Value of Pi = 3.1415

 

The lambda expression must be compatible with the abstract method. This means if you assign () -> “3.1415” to the myInterface instance, the code is illegal and won’t work because the type of String is not compatible with the double as defined in the functional interface.

Let’s look at some other lambda expression example that takes in a parameter.

// MyInterface.java
@FunctionalInterface
public interface MyInterface {
    String reverse(String n);
}
// ParamLambdaMain.java
public class ParamLambdaMain {
    public static void main(String[] args) {
        MyInterface myInterface = (str) -> {
            String result = "";
            for (int i = str.length() - 1; i >= 0; i--)
                result += str.charAt(i);
            return result;
        };

        System.out.println("Lambda reversed = " + myInterface.reverse("Lambda"));
    }
}

When you run the program, the output will be:

 

Lambda reversed = adbmaL

 

The above functional interface only accepts String and returns a string. However, we can make the functional interface generic, so that any value is accepted.Let’s look at how it’s done:

// GenericInterface.java
@FunctionalInterface
interface GenericInterface<T> {
    T func(T t);
}

 

Now, this GenericInterface is compatible with any lambda expression that takes one parameter and returns the value of the same type.

// GenericLambda.java
public class GenericLambda {
    public static void main(String[] args) {
        GenericInterface<String> reverse = (str) -> {
            String result = "";
            for (int i = str.length() - 1; i >= 0; i--)
                result += str.charAt(i);

            return result;
        };

        System.out.println("Lambda reversed = " + reverse.func("Lambda"));

        GenericInterface<Integer> factorial = (n) -> {
            int result = 1;
            for (int i = 1; i <= n; i++)
                result = i * result;
            return result;
        };
        System.out.println("factorial of 5 = " + factorial.func(5));
    }
}

 

When you run the program, the output will be:

Lambda reversed = adbmaL
factorial of 5 = 120

 

3. Method Referencing using Lambda

To reference a method using lambda, a new separator double colon added in Java 8 is used. This method reference can be used anywhere in which it is compatible with the functional interface.

Static method reference syntax is:

ClassName::methodName

Reference to the instance method on specific object syntax is:

objRef::methodName

Constructor Reference syntax is:

ClassName::new

Let’s look at code example for static method reference.

// MyInterface.java
@FunctionalInterface
public interface MyInterface {
    int myFunc(int n);
}

// IntOperations.java
public class IntOperations {
    static int factorial(int n) {
        int result = 1;
        for (int i = 1; i <= n; i++) {
            result = i * result;
        }
        return result;
    }
}

// MethodRefMain.java
public class MethodRefMain {

    static int fact(MyInterface myInterface, int n) {
        return myInterface.myFunc(n);
    }

    public static void main(String[] args) {
        // static method referencing
        int result = fact(IntOperations::factorial, 5);
        System.out.println("5 Factorial = " + result);
    }
}

When you run the program, the output will be:

5 Factorial = 120

 

4. Lambdas and Stream API

The new java.util.stream package has been added to JDK8 which allows Java developers to perform operations like filter, map, reduce the collections like List. With the help of Stream API, we can do either parallel or sequential operations over the stream of data. The java.util.stream.Stream interface which is helpful to do bulk operations

The Stream API would allow us to declare either sequential or parallel operation over the stream of data.

import java.util.Arrays;
import java.util.List;

public class StreamMain {

    public static void main(String[] args) {
        List<String> myList = Arrays.asList("Asia:India", "Asia:Nepal", "NorthAmerica:USA", "Africa:Nigeria", "Europe:UK");

        myList.stream()
                .filter(s -> s.startsWith("Asia")) // filter the data
                .map(String::toUpperCase) // map each data
                .sorted()    // sort the data
                .forEach(System.out::println); // print it
    }
}

When you run the program, the output will be:

ASIA:INDIA 
ASIA:NEPAL

 

Starting with Java 8 Streams? Read our article on Introduction to Java 8 Streams.

 

Summary

In this article, we get a basic understanding of Lambda Expressions in Java.We discussed benefits about the Lambda Expressions and what are the different types of Lambda Expressions in Java.

Spring Interview Questions

Spring Interview Questions

This post is the part of our Interview Questions series and in this post, we will discuss some of the commonly asked Spring Interview Questions during a job interview.

 

1. Spring Beans And Dependency Injection

Spring Beans are the core of Spring Framework. Some questions related to Spring Beans are:

 

Q1. What is Spring Framework?

Spring is known as one of the most popular frameworks for Java Enterprise applications. Spring framework Dependency injection feature can be used on any Java based application (web or non-web).

The core of Spring framework is based on dependency injection design pattern which allows us to easily build decoupled systems.

 

 

Q2. What are the benefits of Spring?

Spring Framework makes it easier to build enterprise Java applications, below are some of the advantages of using it

  • IoC Container: Spring manage the lifecycle of the Spring Beans and configurations using it’s Ioc container, this makes project management and maintenance easier.
  • Versatile: Spring provides flexibility to integrate it with any Java based technologies.
  • Inversion of Control: Spring will take care of injecting required dependencies for our application, we are no longer required to manually search and inject required dependencies for our application.
  • Lightweight: Spring is divided into different modules with a minimal dependency on each other which make it really lightweight and have the flexibility to only use required modules for your application.
  • End to End Development: Spring Framework provides modules for all aspects of application development ranging from Dependency Injection, Persistence, Caching, Business, Web, REST, it’s an ecosystem for developing all type of Java based Enterprise applications.
  • Non-invasive: Spring does not force us to use any Spring based interface or to extend any Spring based class to use its features which give our code flexibility to be used in any other technology. e.g. We can inject dependency using @Inject annotation which is not Spring based annotation, there will be no change in case we want to use Guice as our dependency injection API.
  • Exception Handling: Spring Framework provides multiple options to handle exceptions in a better and more flexible way.

 

 

Q3. What is Dependency Injection?

Dependency Injection is a technique with which we can make our program loosely coupled and inject required dependencies by defining them as Beans using several annotations like @Service, @Component, @Repository, @Controller or a @Bean annotation.

 

 

Q4. What are types of Dependency Injection techniques supported in Spring?

Spring supports three types of Dependency Injection

  • Setter based Dependency Injection.
  • Constructor based Dependency Injection.
  • Field Injection

 

Q5. What does bean scopes Spring supports?

There are five bean scopes supported by Spring:

  1. Singleton
  2. Prototype
  3. Request
  4. Session
  5. Global-session

 

Q6. Explain bean scopes in Spring?

Bean scopes define the lifecycle of a Bean. More about bean scopes can be read

  1. singleton(default*)
    Scopes a single bean definition for a single object instance per Spring IoC container.
  2. prototype
    Scopes a single bean definition for any number of object instances.
  3. request
    Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
  4. session
    Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
  5. global session
    Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

For more information read Bean scopes

 

Q7. What is the recommended way to inject beans in Spring?

The recommended way to inject dependencies into Spring components is by using constructor injection. This should be followed by any compulsory dependencies needed. For optional dependencies, setter injection should be used.

 

Q8. What are the different modules/subprojects of the Spring?

  1. Spring Core.
  2. Spring JDBC
  3. Spring ORM
  4. Spring AOP
  5. Spring MVC

 

Q9. What Design patterns are used in Spring framework?

  1. Singleton pattern in Singleton scoped beans
  2. Model View Controller in Spring MVC
  3. Data Access Object in Spring DAO support
  4. Front Controller in Spring Dispatcher Servlet
  5. Template Method Pattern in Spring JDBC support
  6. Adapter Pattern in Spring MVC and Spring Web
  7. Proxy Pattern in Spring AOP support
  8. Factory Pattern in Bean Factory classes

 

Q10. What are Spring profiles?

Spring profiles allow us to configure Spring Beans based on the profile of dev, QA, staging, production etc. The use of profiles is that we can make same Spring app which points to different databases or message broker instances with a difference of just a flag. Please read our article on Spring Profiles for more detail.

 

Q11. What does @Required annotation do?

@Required annotation marks a bean as a required bean which means it needs to be configured at configuration time. Otherwise, the Spring container will throw a BeanInitializationException exception.

 

 

Q12. What does @Autowired annotation do?

The @Autowired annotation is used with fields or methods for injecting a bean by type. This annotation allows Spring to resolve and inject collaborating beans into the required bean.

 

 

Q13. In how many ways we can handle Exceptions in a Spring project?

  1. By using @ExceptionHandler annotation at the Controller level. This helps in managing an exception in a particular controller without affecting complete app flow.
  2. Using HandlerExceptionResolver, we can handle exceptions at the complete application level.
  3. By using @ControllerAdvice annotation, we can configure Exception handlers for application-level control and still keep the code very clean and modular.

 

Q14. What is the difference between annotations like @Component, @Controller, @Service and @Repository?

Out of all, @Component annotation is a generic annotation. So anything which is a Controller, Service or a Repository, it’s a Component as well. For specifics, let’s look at each of one of these:

  • @Controller: This annotation enables the detection of @RequestMapping annotation in the class. It also indicates that this class is a Controller.
  • @Service: It indicates that this class handles the business logic of the application and ought to call the @Repository classes for DB interaction.
  • @Repository: This indicates that the class defines a DB interface. It makes sure that the platform-specific exceptions are caught again and thrown again as Spring specific unchecked exceptions

 

 

In this article, we discussed some the commonly asked Spring Interview Questions during a job interview.We will be covering Interview questions of the other modules of the Spring framework in a different post.

Let us know in case you feel any modification or edit is required or you think that we are missing some important questions.

How to Kill Java Thread

How to Kill Java Thread

In this article, we will discuss the clean way to Kill Java Thread, this is really necessary to understand as Java had already deprecated Thread.stop() methods.

 

Introduction

Oracle deprecated Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit due to some of the underlying thread safety issues.  There are few recognized and well-accepted ways to accomplish this and in this article, we will be covering 2 approached to Kill a Thread in Java.

  • Using a Flag
  • Interrupting a Thread.

 

1. Use a Flag

One of the easy approaches is to use thread to indicate if a Thread is running or not and use this flag to take corrective action based on your requirement, here is a sample code outlining how to Kill Java Thread using a flag.

public class KillThreadUsingFlag implements Runnable {


    private final AtomicBoolean running = new AtomicBoolean(false);
    private Thread thread;

    /**
     * When an object implementing interface <code>Runnable</code> is used to create a thread,
     * starting the thread causes the object's <code>run</code> method to be called in that
     * separately executing thread. <p> The general contract of the method <code>run</code> is that
     * it may take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {

        while (running.get()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
            }
        }
        System.out.println("Shutting down thread");
    }

    public void shutdown() {
        running.set(false);
    }

    public void start() {
        thread = new Thread(this);
        thread.start();
    }

    public static void main(String[] args)
            throws InterruptedException {
        KillThreadUsingFlag process = new KillThreadUsingFlag();
        process.start();
        Thread.sleep(5000);
        process.shutdown();
    }
}

In the above example. we can control execution by setting our running variable to false.In our example, we have used AtomicBoolean for concurrency, in case you do not want to use it (which is not recommended), you need to make sure that Boolean flag used by you in your code should be volatile.

 

2. Interrupting a Thread

Above code looks good but have some main points which need to be taken into account before we take above approach

  • It will become more complicated in case we have lots of threads and we need to ensure that those are finished by using join() method.
  • Do we really need to define a Boolean flag as Java already provide this feature using interrupted flag?
public class InterruptedExceptionExample implements  Runnable {


    private final AtomicBoolean running = new AtomicBoolean(true);


    /**
     * When an object implementing interface <code>Runnable</code> is used to create a thread,
     * starting the thread causes the object's <code>run</code> method to be called in that
     * separately executing thread. <p> The general contract of the method <code>run</code> is that
     * it may take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        try{

            while (running.get()){
                for(int i =0; i<3 ; i++){
                    System.out.println(i);
                }

                Thread.sleep(2000);
            }
        }
        catch (InterruptedException e){
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<?> future = executor.submit(new InterruptedExceptionExample());
        Thread.sleep(3000);
        executor.shutdownNow();
    }
}

 

There are couple of things which are really important in this code block

  • We are not swallowing the exception but passing it on to the system to ensure corrective action is being taken by system based on this exception

In the above example, we caught InterruptedException and immediately used Thread.currentThread().interrupt()  to interrupt our thread immediately.This is required since the interrupted flag is cleared once the exception is thrown and it can cause some issue in case our code is running in the nested loop.

Just to summarize, Thread.interrupt() is the preferred/recommended way to cleanly Kill Java Thread if you still want to use flag approach you may have to wait for all the blocking operations to finish before you can use your flag based logic.

 

Summary

Java Concurrency is always always a complex part of the JDK and working with threads can add more complexity if we are not aware of the inner working mechanism of the JDK. In this post, we covered different ways to Kill Java Thread. We discussed a flag based approach to handle this and finally, we covered mechanism of interrupting a thread which is known as better and cleaner way to shut down threads in Java.

Spring WebApplicationInitializer

Spring WebApplicationInitializer

In this article, we will get an understanding of  Spring WebApplicationInitializer interface along with a detailed analysis of the benefits and configurations of Spring WebApplicationInitializer.

 

Introduction

Dispatcher Servlet is known as an entry point for Spring MVC based web applications, you can think of Dispatcher Servlet as a gatekeeper for MVC application responsible to understand the request, send it to correct place and responsible to send the response back to the calling party.

Spring 3.1 Brough support for the Servlet 3 API, before that we can only register Servlet Dispatcher with Servlet container via the standard Web application web.xml file.

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

    <display-name>Spring3 MVC Application</display-name>

    <servlet>
        <servlet-name>spring-web</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-web</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

With Spring support for Servlet 3.0 Specification, web.xml is optional and we can manage all our web application using Java Annotations.

One of the natural questions will arise in your mind is “If we are not registering Dispatcher Servlet than how Spring will create/bootstrap Dispatcher Servlet for our application?

Spring WebApplicationInitializer is the answer to your above question which was introduced with Spring 3.1.

 

1. What is Spring WebApplicationInitializer?

Spring WebApplicationInitializer is Servlet 3.0 + implementation to configure ServletContext programmatically in comparison to the traditional way to do this using web.xml.

 

2. Hybrid Configuration

We have 2 ways to replace traditional web.xml using Spring WebApplicationInitializer, in this one we will discuss a mix of replacing configuration using Java Annotation and XML based Spring configuration.

public class CustomWebAppInitializer implements WebApplicationInitializer {
    /**
     * Configure the given {@link ServletContext} with any servlets, filters, listeners
     * context-params and attributes necessary for initializing this web application. See examples
     * {@linkplain WebApplicationInitializer above}.
     *
     * @param servletContext the {@code ServletContext} to initialize
     * @throws ServletException if any call against the given {@code ServletContext} throws a {@code
     *                          ServletException}
     */
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        XmlWebApplicationContext applicationContext = new XmlWebApplicationContext();
        applicationContext.setConfigLocation("location of spring config xml file");

        //Dispatcher servlet configuration

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(applicationContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }

Above approach looks good, clean and preferred way to do it but this is not purely Java code based approach as we are still using web.xml in our code to read this configuration.

 

3. WebApplicationInitializer With Java Annotation

Let’s change our previous code to purely Java Annotation-based configuration.We will try to use Spring @Configuration classes in place of traditional XmlWebApplicationContext.

public class CustomWebAppInitializer implements WebApplicationInitializer {
    /**
     * Configure the given {@link ServletContext} with any servlets, filters, listeners
     * context-params and attributes necessary for initializing this web application. See examples
     * {@linkplain WebApplicationInitializer above}.
     *
     * @param servletContext the {@code ServletContext} to initialize
     * @throws ServletException if any call against the given {@code ServletContext} throws a {@code
     *                          ServletException}
     */
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(Application.class);

        // Manage the lifecycle of the root application context
        servletContext.addListener(new ContextLoaderListener(rootContext));

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher =
                servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
}

 

Let’s try to understand above example for better clarity.

As we are using Java-based annotation in place for XML configuration, we are going to use AnnotationConfigWebApplicationContext for this

AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();

We need to register our context, this can be easily done by registering our custom configuration class.

rootContext.register(Application.class);

Let’s say your custom configurations are spread across multiple classes and you want to use all of these configurations, Spring WebApplicationInitializer provide a way to specify root package to be scanned for configuration classes.

rootContext.setConfigLocation("com.javadevjournal.app.config");

the application context is in place now, next step is to add our ContextLoaderListner to the ServletContext which will be responsible to load the context

// Manage the lifecycle of the root application context
servletContext.addListener(new ContextLoaderListener(rootContext));

The final step of our example is creating and registering Dispatcher servlet, which is the entry point of our application.

// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher =
        servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
 
3.1 Web.xml and Java Annotation Caveats

Please be aware of the fact that web.xml and Spring WebApplicationInitializer configurations are not mutually exclusive, this means you can register one servlet in your application’s web.xml while you can use WebApplicationInitializer to register another servlet for your application.In case you have a web.xml file under WEB-INF/web.xml, it’s version must be set to 3.0 or greater else ServletContainerInitializer will completely ignore your web.xml file.

 

Annotation-based configurations offer a lot of advantages and these configurations are now becoming de facto standards for the new Spring-based applications, annotations are more concise and they normally add clear context to the declaration, however, there are certain cases where this is not a preferred way 

  • I still want to separate out my code and configurations
  • Any third party solution which is outside of our control and we can not customize it.

 

Summary

In this article, We got an understanding of  Spring WebApplicationInitializer interface. we covered traditional way to initialize our Spring application. We covered mix way (use configuration and annotation) for our application configuration. In the last part, we covered the new way (100% java base) configuration.

Spring WebApplicationInitializer is really powerful and with new Servlet 3.0 specification, it provides a more flexible way to configure our application. In the next article, we will be covering web.xml and Initializer in more detail.

Functional Interfaces in Java 8

Functional Interfaces in Java 8

This post works as an introduction to the Functional Interfaces in Java 8. We will be covering some of the basics of the Functional Interfaces introduced in Java 8.

 

Introduction

Java has always been called as OOP (Object Oriented Programming) language. Functions do not exist independently in Java and everything is part of Class and use to class/object to invoke any function (ie, JNI). Functional Programming Language is written independent functions and uses them when required such as C++, JavaScript.

Function Interface was introduced in Java8 as new features along with Stream API, Time API, Lambda Expression, etc., Function Interface having only one abstract method which means interface contains only one abstract method and it can have multiple default methods.

 

1.FunctionalInterface Example 

@FunctionalInterface annotation was introduced along with other annotation in Java 8 which can be used to validate at the compile time that can’t have more than one method beside default.

Let’s create a simple example to understand few details of the @FunctionalInterface.

@FunctionalInterface
public interface Account {

    int returns();

    default void printDetails() {
        System.out.println("Default Methods");
    }
}

An interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface’s abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere (ie., abstract methods that override the method in the object).

@FunctionalInterface
public interface Account {

    int returns();

    default void printDetails() {
        System.out.println("Default Methods");
    }

    /*
     * Overridden from Object class
     */
    public String toString();

    public int hashCode();

}

FunctionalInterface annotation is not mandatory to use because of the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.

Java earlier version having a single abstract method in the interface and they were known as simple abstract method interface e.g.,Runnable Interface (Run method), Comparator Interface.

 

2.Functional Interfaces Type 

The declaration of a functional interface allows a functional interface type to be used in a program by the developer and these are segregated as four kinds of functional interface type based on a declaration.

 

Another interesting part is Interface can extend another interface and In this scenario, Interface extending in functional and it doesn’t declare any new abstract methods then the new interface is functional which will satisfy the definition.

public interface Bank {

    public void openAccount();
}

Account interface extends Bank interface which has only one OpenAccount method and Account interface doesn’t have any abstract method but still, it is valid functional Interface.

@FunctionalInterface
public interface Account extends  Bank {}

Let see one more example, consider while inherits two abstract which have the same signature.

public interface SocialMedia {
  public void OpenAccount();
}

In this case, still, the inherited methods logically represent a signal method so Account is a function interface.

@FunctionalInterface
public interface Account extends SocialMedia {
}

 

Consider above example, if one is return type substitutable then Account causes compile time error because it’s inheriting two methods.

 

interface Bank {public void OpenAccount();}
interface SocialMedia {public boolean OpenAccount();}

There are numbers of functional interfaces defined under java.util.function package, some of the useful interfaces are

  • Consumer
  • Function
  • Supplier
  • Predicate

 

2.1  Predicate Example

import java.util.function.Predicate;;

/**
 * @author Arunchandu
 */
public class PredicateTestExample {

    public static void main(String[] args) {

        Predicate<String> i = (name) -> name.contains("java");
        System.out.println(i.test("Thank you for Learning from javadevjournal.com"));
    }

}

 

2.2  Pass Function Example

import java.util.function.Function;

public class PassFunction {

    public static void main(String[] args) {
        int percentage = 5;
        String result = calc((amount) -> "Tax : " + ((amount * 100) / percentage), 10);

        System.out.println(result);

    }

    public static String calc(Function<Float, String> bi, float i) {
        return bi.apply(i);
    }

}

 

Summary

In this post, we got an introduction to the Functional Interfaces in Java 8. We covered some of the aspects of functional interfaces along with few interesting functional interfaces introduced in Java 8.

If you are starting with Java 8, read our following articles on Java 8

  1. Introduction to Java 8 Streams
  2. java 8 optional
  3. Java 8 StringJoiner

Introduction to Java 8 Streams

Introduction to Java 8 Streams

In this post, we will get a quick Introduction to Java 8 Streams API, a new feature introduced in Java 8.We will try to get a high level of understanding as what is stream and how this can be used in our day to day work.

 

Introduction

Streams are one of the most important APIs introduced in Java 8 and completely changes the way we do processing of Collections in Java. This is in line with the theme of Java since past few versions where advances in hardware are exploited by the language.

 

1. Why Java 8 Streams

Before diving into ‘What’ of Streams, let us get into ‘Why’. Why were Streams introduced and what
problem they solve?

Let us see the code below:

private static HashMap<String, Integer> myIterator(List<String> inList) {
    Iterator<String> thisIterator = inList.iterator();
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    while (thisIterator.hasNext()) {
        String str = thisIterator.next();
        if (str.length() > 5) {
            map.put(str, str.length());
        }
    }
    return map;

}

Above code is not doing anything fancy or complicated but it takes in a List of String, calculates the length of each String in List and puts the String, String Length in a HashMap if length greater than 5. It is definitely solving our problem but there are multiple problems with above code.

  1. The code is sequential in nature and in spite of my computer being a Quad core system, I am not exploiting computer’s processing power here.
  2. Simply, too much code for a simple task.
  3. As a programmer, I need to work on the lower level aspects of the program. I have to take care of ‘how’ the iteration takes place apart from the program logic. Such programmer driven iteration is called External Iteration. It can have optimization issues in complex and data-intensive programs.

 

2. Code Simplifaction using Java Streams

Java Streams help us address the above-mentioned issues by completely abstracting out the low-level parallelism logic and Iteration logic.Putting in the most simple way, Java Streams convert Collections to a Stream, process the elements in parallel by performing multiple operations and again gather the final elements into a Collection.

Java Stream API helps us do above mention by implementing internal iteration. It lets the framework perform a sequential and parallel execution, mapping elements and criteria based filtering. Java framework is in control of the resulting iteration and lets the developer fully concentrate on the data and various operations to be performed on it.

Java Stream API implements functional interfaces as its API methods, which ties up well with Lambda expressions, which is another pillar of Java 8. Together they make the Java 8 a true ‘functional’ language.

Thus, when we use Java Streams, the code mentioned above turns into a single line code.


private static Map<String, Integer> myIterator(List<String> inList) {

    return inList.stream().filter(str -> str.length() > 5).
            collect(Collectors.toMap(str -> str, str -> str.length()));
}

Here inList is a List of Strings. Stream method takes the inList and streams it into a filter. Filter passes only those Strings which meet the criteria (String.length>5). Collect method takes in the filtered Strings and sends them to Collector.toMap() function which inserts the String and their Lengths in the Map.

In a single line of code, we utilize the Streaming, Filtering and Collection mechanisms of the API thus writing a more efficient code.

 

3. Steams API Benefits

let’s see other important aspects of Streams.

Streams are on-demand Data Structures. They don’t store data and instead take in a Data Structure(mainly Collections) as the source to produce a pipeline of that Collection. On this pipeline, desired functions can be called further to harness the power of in-memory computation.

Streams support Parallel Processing and Sequential Processing both, giving the developer options to use whatever mechanism as per the requirement. For large collections, Parallel Processing can work wonders in terms of achieving great performance.

Streams support Lazy computation, that means we do these operations only when we need it and not when they are defined in the Streams.This leads to higher performance and optimization of the programs than the traditional methods.

Streams have two types of Operations: Intermediate and Terminal. All those Stream operations which return a new Stream are called intermediate operations. These never return the final result of the operations and help in building a pipeline from one operation to another. filter and map are two such operations.

All Stream operations which return a result are Terminal operations. They are eager computations which process Stream elements before returning results and they consume the Stream. After consumption by these operations, Streams are no more available for further processing. They can be identified by their return types as they would not produce any further Streams. Examples are:forEach, toArray, min, max etc.

 

Summary

This was a very high level and a brief Introduction to Java 8 Streams API. We discussed what are the benefits and features brought by Java Streams and how they can be utilized to write more concise and easily readable code.

Stay tuned to our website for further content on Streams and other in-depth content in Java.If you are interested to learn about new features of Java 8, read 

Java 8 optional

Java 8 StringJoiner

Spring Framework Annotations

 Introduction to Spring Framework Annotations

In this post, we will get a quick introduction to Spring Framework Annotations. We will explore different annotations along with few of the internal details for these Spring Framework Annotations.

 

Introduction

Java 5.0 introduced support for the annotations and very quickly it became one of the preferred ways, Spring Framework was quick to adopt this and with 2.5 Spring Framework started support for annotations.

Though we can still use XML based configurations to control/manage our Spring application, Spring Framework Annotations are now becoming a defacto standard for Spring-based enterprise applications.

 

1. Spring Core Annotation

In this section, we will be covering Spring Framework Core Annotations.

1.1 @Required

@Required annotation is applied to the bean setter method to enforce require property.It can be used when we want to make sure that a specific bean is required to be injected by Spring, in case required Spring bean is unable to inject the required bean, BeanInitializationException is thrown.

@Required
public void setClient(OkHttpClient client) {
    this.client = client;
}

 

1.2 @Autowired

@Autowired annotation is used to inject object implicitly, We can apply this annotation to fields, setter methods, and constructors.

You can use @Autowired annotation on the constructor, Spring will inject dependency at the time of object creation. Please note that you can only use this annotation to the maximum of 1 constructor for a given class.

@Autowired
public WebConfiguration(RequestResult result){
    this.requestResult=result
}

For @Autowire annotation, Spring does not have the requirement for the constructor to be public.

We can also use @Autowire annotation on the class property 

@Autowired
private OkHttpClient client;

@Autowired
private ObjectMapper jacksonObjectMapper;

The third option is to use this annotation on the setter method, Spring internally will try to perform injection by Type.

@Autowired
public void setClient(OkHttpClient client) {
    this.client = client;
}

With Spring 4.3, @Autowire has become optional on classes with a single constructor, so for the below code, Spring will try to inject instance of the Customer (even we do not have @Autowire annotation)

@Component
public class Customer {
    
   private Order order;

    public Customer(Order order) {
        this.order = order;
    }
}

 

1.3 @Qualifier

When you need more control over the dependency injection process, you should consider using @Qualifier annotation.The qualifier annotation helps disambiguate bean references when Spring would otherwise not be able to do so, in short, this annotation is used to avoid confusion in the dependency injection.

To understand it more clearly, let’s take a simple example of HelloWorldService, let’s assume that we have 2 implementations of our HelloWorldService

public interface HelloWorldService {
    
    void sayHello();
}

public class HelloWorldService1 implements  HelloWorldService {
    
    @Override
    public void sayHello() {
        
    }
}

public class HelloWorldService2 implements  HelloWorldService {
    
    @Override
    public void sayHello() {
        
    }
}

In case we want to Inject our HelloWorldService1 using @Autowire annotation, Spring will not know which one of the two implementations to inject.

public class HelloWordTest {
    
    @Autowired
    private HelloWorldService helloWorldService;
}

To handle all similar issues where we want to let Spring know about which dependency to pick and inject, we can use @Qualifier annotation.

@Autowired
@Resource(name = "helloService1")
private HelloWorldService helloWorldService;

 

1.4 @Bean

@Bean annotation is used to create bean in the Spring Framework, this annotation is used at the method level

@Bean
public Customer customer() {
    // instantiate and configure customer obj
    return customer;
}

By default,  strategy for determining the name of a bean is to use the name of the @Bean method, however, if we want to explicitly name our bean, we can always use “name” or “alias” value to do that.

@Bean({"user", "customer"})
public Customer customer() {
    // instantiate and configure customer obj
    return customer;
}

 

1.5 @Configuration

This annotation is used at the class level which defines Beans, think of @Configuration annotation as configuration using Java class (than traditional XML file to define Spring Beans)

@Configuration
public class ApplicationConfig {
  
    @Bean
    public OkHttpClient client(){
        return new OkHttpClient.Builder()
                .build();
    }

   @Bean
    public CommonsRequestLoggingFilter requestLoggingFilter() {
        CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
        loggingFilter.setIncludeClientInfo(true);
        loggingFilter.setIncludeQueryString(true);
        loggingFilter.setIncludePayload(true);
        loggingFilter.setIncludeHeaders(false);
        return loggingFilter;
    }
}

 

1.6 @ComponentScan

This annotation is used to configures component scanning directives for use with @Configuration classes, we can specify base package from where we want Spring to scan packages.If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

 

1.7 @Lazy

Spring by default use eager initialization strategy i.e all autowired dependencies will be created and configured at startup.If we do not want this to happen, we can use @Lazy annotation to ensure he @Bean or @Component will not be initialized until referenced by another bean or explicitly retrieved from the enclosing BeanFactory.

@Configuration
@Lazy
public class AppConf {

    @Bean
    public MyBean bean() {
        return new MyBean();
    }

    @Bean
    public MyBean1 bean1() {
        return new MyBean1();
    }

    //Bean2 will be eagerly loaded by Spring
    @Bean
    @Lazy(value = false)
    public Bean2 bean2() {
        return new Bean2();
    }
}

 

1.8 @Value

This is at the field or method/constructor parameter level that indicates a default value expression for the affected argument. This is very similar to @Autowire annotation but @Value annotation will be used to inject values from properties.

To understand it more clearly, let’s take an example where we want to get some of the values from the property file, Let’s define our property file

user.name=Java Dev Journal
language=java

Here is our Java code

@Value("user.name")
private String username;

@Value("language")
private String language;

Please read @ConfigurationProperties in Spring Boot to understand how it works for Spring Boot.

 

In this section, we will be covering Stereotype Annotations provided by Spring Framework.

 

1.9 @Service

This is a class level annotation indicates that an annotated class is a "Service", Apart from the fact that it is used to indicate that it’s holding the business logic, there’s no noticeable specialty that this annotation provides.

@Service("helloService")
public class HelloWorldService1 implements  HelloWorldService {

    @Override
    public void sayHello() {

    }
}

 

1.10 @Repository

This annotation is used on the classes which are working directly with the DB layer, @Repository annotation indicates that an annotated class is a "Repository".One of the different thing being performed by classes annotated with @Repository annotation is to catch Platform specific exceptions and re-throw them as one of Spring’s unified unchecked exception.

 

1.11 @Component

This annotation is used to indicate a Spring-powered component.This is a general-purpose stereotype annotation indicating that the class is a spring component.If we check definitions of @Service or @Repository annotations

@Component
public @interface Service {
   //
}

@Component
public @interface Repository {
   //
}

we can safely say that @Service or @Repository annotations are special kinds of @Component annotation.

 

Summary

In this post, we get an introduction to Spring Framework Annotations. We checked a different kind of  Annotations provided by Spring Framework with information about when to use these Annotations.

In the next article, we will cover some of the important Annotations provided by Spring Boot and Spring MVC framework.

Spring Boot Logging

Introduction to Spring Boot Logging

Logging is one of the important features of any enterprise application, in this post we will get an understanding of Spring Boot Logging mechanism along with few of configuration details.

 

Introduction 

Spring Boot comes with many ready to use features and Logging is one of those features, by default Spring Boot use Commons Logging for its internal logging but it also provides options to use/configure any other log mechanism.

If we are using Spring Boot Starters for our application, Logback will be used for logging by default unless we want to use any other logging API.

 

1.  Understand Log Output

Before we get into more details, let’s take a quick look at the default log out for the Spring Boot application to understand it more clearly.

2017-11-07 20:26:37.317  INFO 5388 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot[email protected]53404716: startup date [Tue Nov 07 20:26:34 PST 2017]; root of context hierarchy
2017-11-07 20:26:37.404  INFO 5388 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[GET || POST]}" onto public java.lang.String com.umesh.rest.web.controller.DemoController.sayHello(javax.servlet.http.HttpServletRequest) throws java.io.IOException
2017-11-07 20:26:37.407  INFO 5388 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/demo/greeting],methods=[GET]}" onto public java.lang.String com.umesh.rest.web.controller.LoggingDemoController.sayHello()
2017-11-07 20:26:37.409  INFO 5388 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-07 20:26:37.410  INFO 5388 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)

There are certain things to understand above log output

  • Date and Time: First section indicates date and time of the log output. (e.g. 2017-11-07 20:26:37.317)
  • Log Level: Second main output indicated log level (e.g. INFO in our case).
  • Number as third output indicates process id (e.g. 5388)
  • — indicated separator
  • Output enclosed in [] indicates Thread name.
  • Last 2 output indicates Logger Name / Log Class name and logs message.

 

2.  Example

To understand how to configure and control Spring Boot Logging, let’s create a simple Controller with few log statements in it.


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Controller public class LoggingDemoController {
    
 private final Logger log = LoggerFactory.getLogger(this.getClass());
 
 @GetMapping("/demo/greeting") public String sayHello() {
  log.info("Info log statement for LoggingDemoController");
  log.warn("Warn log statement for LoggingDemoController");
  log.error("Error log statement for LoggingDemoController");
  return "greeting";
  
 }
 
}

On running above application by opening http://localhost:8080/demo/greeting, we can see following output in the console.

2017-11-07 20:43:41.566  INFO 5430 --- [io-10070-exec-4] c.u.r.w.c.LoggingDemoController          : Info log statement for LoggingDemoController
2017-11-07 20:43:41.567  WARN 5430 --- [io-10070-exec-4] c.u.r.w.c.LoggingDemoController          : Warn log statement for LoggingDemoController
2017-11-07 20:43:41.567 ERROR 5430 --- [io-10070-exec-4] c.u.r.w.c.LoggingDemoController          : Error log statement for LoggingDemoController

Spring Boot Logging API provides a number of features which help us to decouple out code

  • We are using SFL4J facade for our logging thus we are decoupled from underlying Logback API.
  • By using it, we are free to replace Logback with any other logging API without changing our code base.

 

3.  Log File Output

by default, Spring Boot Logging API will log output to the console and not to any file, for writing log output to a file, we can set logging.file or logging.path property in the application.properties file.

logging.file =/work/demo/log/loggingdemocontroller.log
//or
logging.path= /work/demo/log

Please note that if in case we use logging.path property, Spring Boot will write a file with a name spring.log to the specified directory.

 

4.  Setting Log Levels

Spring Boot provides an easy way to configure and set logging levels for your application.We can use application.properties file to configure the desired Logging level for our application by using ‘logging.level.*=LEVEL’. Let’s use our previous example to get an understanding of setting log level in our application. We will configure our log level to output only WARN and ERROR logs.

application.properties

logging.level.com.javadevjournal.rest= WARN

On running above application by opening http://localhost:8080/demo/greeting, we can see following output in the console.

2017-11-08 20:05:13.362  WARN 8647 --- [nio-8080-exec-1] c.j.r.w.c.LoggingDemoController          : Warn log statement for LoggingDemoController
2017-11-08 20:05:13.362 ERROR 8647 --- [nio-8080-exec-1] c.j.r.w.c.LoggingDemoController          : Error log statement for LoggingDemoController

Since we configured our log level to the WARN, Spring Boot Logging API will only output log statements for WARN and higher (in our case WARN and ERROR).

The root logger can be configured using logging.level.root.

 

5.  Configure Logback Through External File.

For most of the applications, Spring Boot Logging default configurations are more than sufficient, however, for large-scale enterprise applications have complex logging requirements and Spring Boot provide a way to configure it through the external XML file.

You can put logback.xml or logback-spring.xml file in the root of your classpath it will be picked up from there by Spring Boot. Please note that logback-spring.xml is preferred over the logback.xml file by Spring Boot.

here is a sample logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml"/>
    <logger name="com.javadevjournal.rest" level="WARN" additivity="false">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </logger>
</configuration>

If you want to get more understanding of the System properties which the LoggingSystem takes care of creating for us, please have a look at base.xml file inside spring-boot jar and especially the following line 

<property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/spring.log}"/>

 

6. Spring Boot Profiles in Logging

Spring Profiling is an excellent concept which provides us the flexibility to define properties for the different environment without any code change. Spring Boot provides the same profile mechanism for the logback configuration by using the <springProfile> element. Let’s use an example to understand how you can define different logging level for DEV and Production environments using the same logback configuration.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    <springProfile name="dev">
        <logger name="com.javadevjournal.rest" level="DEBUG" additivity="false">
            <appender-ref ref="CONSOLE" />
        </logger>>
    </springProfile>
    <springProfile name="production">
        <logger name="com.javadevjournal.rest" level="WARN" additivity="false">
            <appender-ref ref="FILE" />
        </logger>
    </springProfile>
 </configuration>

Read Spring Profiles to get an understanding of how to use Spring Profiles feature for your application. 

 

7. Configure Log4j

Not all application want to use default logging configuration and it holds true for Spring Boot Logging mechanism, however, Spring Boot provides an easy way to use any other logging framework.In case you want to use Log4j2 for logging configuration, all you have to add the log4j2 starter in your application (no other complex configurations).

Please be aware that if If you are using the starters for your application, you need to exclude logback and then include log4j 2 instead.

Here is a sample configuration to use log4j for your application.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

 

Summary 

In this post, we explored different features of the Spring Boot Logging API, we discussed what are the default configurations provided by Spring Boot along with options to configure or customize these options.

Logging is one of the main tool in the application development and with complex enterprise applications, logging requirement can become very complex with the time, however, Spring Boot Logging API provides all the tools to handle all these complex use cases with minimal configuration changes.

If you are starting with Spring Boot, please read Building an Application with Spring Boot to start your journey with Spring Boot