Saturday 21 July 2018

Spring boot: Generate banner programmatically

In my previous post, I explained various ways to add banner to an application. In this post, I am going to explain how to set the banner programmatically.

a. Create the custom banner by implementing 'org.springframework.boot.Banner' interface.
public class MyBanner implements Banner {

}

b. Set the banner to spring application.
SpringApplication app = new SpringApplication(Application.class);
app.setBanner(new MyBanner());

Find the below working application.

MyBanner.java
package com.sample.myApp;

import java.io.PrintStream;

import org.springframework.boot.Banner;
import org.springframework.core.env.Environment;

public class MyBanner implements Banner {

 @Override
 public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) {
  out.println("**********************************************");
  out.println("*\n**\n***");
  out.println("My Custom Banner");
  out.println("*\n**\n***");
  out.println("***********************************************");
 }

}

Application.java
package com.sample.myApp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Application {

 public static void main(String args[]) {
  SpringApplication app = new SpringApplication(Application.class);
  
  app.setBanner(new MyBanner());
  
  ConfigurableApplicationContext appContext = app.run(args);
  
  appContext.close();
 }
}

When you ran the application, you can able to see below banner in the console.
**********************************************
*
**
***
My Custom Banner
*
**
***
***********************************************







Previous                                                 Next                                                 Home

No comments:

Post a Comment