SpringExamples

Spring Boot Tutorial

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run". We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.

Features

  1. Create stand-alone Spring applications
  2. Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
  3. Provide opinionated 'starter' POMs to simplify your Maven configuration
  4. Automatically configure Spring whenever possible
  5. Provide production-ready features such as metrics, health checks and externalized configuration
  6. Absolutely no code generation and no requirement for XML configuration

Spring boot disable banner example

By Admin | Filed Under: Spring Boot

Learn two ways to disable custom start-up banner in Spring Boot applications.

1. Set Banner Mode to OFF – application.properties

Set the banner mode to OFF.

spring.main.banner-mode=OFF

2. Use SpringApplication.setBannerMode() method

Use setBannerMode(Banner.Mode.OFF) in @SpringBootApplication class.

import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
	public static void main(String[] args) 
	{
		SpringApplication app = new SpringApplication(Application.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);
	}
}
Sourcecode Download

Spring boot custom banner example

By Admin | Filed Under: Spring Boot

Learn how to configure custom start-up banners in Spring Boot applications.

1. Create text file containing custom ASCII art

  1. Create an ASCII art from any online tool such as this.
  2. Name the file banner.txt.
  3. Place the text file with ASCII art in /resources folder.

2. Set Banner Mode

Set the banner mode to either CONSOLE or LOG.

spring.main.banner-mode=CONSOLE
Do not use mode OFF. It will disable the display of banner.
Sourcecode Download

Spring boot change context path and server port

By Admin | Filed Under: Spring Boot

If you want to change the application context path (application root) and server port for any spring boot application, you can utilize any of below two methods:

1. application.properties file

Use server.port and server.contextPath properties.

#server port
server.port=9000

#application root
server.contextPath=/springexamples

2. Customize WebServerFactoryCustomizer

Implement WebServerFactoryCustomizer interface and override customize() method.

import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;

@Component
public class CustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

	@Override
	public void customize(ConfigurableServletWebServerFactory server) {
		server.setPort(9000);
		server.setContextPath("/springexamples");
	}

}
Sourcecode Download

Spring boot CommandLineRunner example

By Admin | Filed Under: Spring Boot

In Spring boot projects, CommandLineRunner interface is used to run a code block only once in application’s lifetime – after application is initialized.

CommandLineRunner can be used in two ways:

  1. Using CommandLineRunner as @Component

    ApplicationStartupRunner class implements CommandLineRunner interface.

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    
    @Component
    public class ApplicationStartupRunner implements CommandLineRunner 
    {
        protected final Log logger = LogFactory.getLog(getClass());
     
        @Override
        public void run(String... args) throws Exception {
            logger.info("ApplicationStartupRunner run method Started !!");
        }
    }
    
  2. Implement CommandLineRunner in @SpringBootApplication

    CommandLineRunner interface is implemented on Application class, so override the run() here itself.

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class Application implements CommandLineRunner 
    {
    	protected final Log logger = LogFactory.getLog(getClass());
    	
        public static void main( String[] args )
        {
        	SpringApplication.run(Application.class, args);
        }
        
        @Override
        public void run(String... args) throws Exception {
        	logger.info("ApplicationStartupRunner run method Started !!");
        }
    }
Sourcecode Download

Spring boot embedded jetty server example

By Admin | Filed Under: Spring Boot

By default, spring boot uses embedded tomcat server to run the applications. You can use embedded jetty server to launch your applications – in two simple steps:

  1. Exclude tomcat server dependency
  2. Include jetty server dependency

1. Embedded Jetty Server Configuration Example

<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.springexamples.demo</groupId>
		<artifactId>SpringExamples</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<groupId>com.springexamples.demo</groupId>
	<artifactId>embedded-jetty-server</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>embedded-jetty-server</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-tomcat</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jetty</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>

2. Jetty Server Demo

Now run the application and observe the console output.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.1.RELEASE)

2018-05-05 19:55:03.344  INFO 3764 --- [           main] com.springexamples.demo.Application      : Starting Application on user-PC with PID 3764 (C:\Users\user\git_springexamples\SpringExamples\embedded-jetty-server\target\classes started by user in C:\Users\user\git_springexamples\SpringExamples\embedded-jetty-server)
2018-05-05 19:55:03.458  INFO 3764 --- [           main] com.springexamples.demo.Application      : No active profile set, falling back to default profiles: default
2018-05-05 19:55:03.615  INFO 3764 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.ser[email protected]e136d3: startup date [Sat May 05 19:55:03 IST 2018]; root of context hierarchy
2018-05-05 19:55:04.802  INFO 3764 --- [           main] org.eclipse.jetty.util.log               : Logging initialized @2336ms to org.eclipse.jetty.util.log.Slf4jLog
2018-05-05 19:55:05.002  INFO 3764 --- [           main] o.s.b.w.e.j.JettyServletWebServerFactory : Server initialized with port: 8080
2018-05-05 19:55:05.004  INFO 3764 --- [           main] org.eclipse.jetty.server.Server          : jetty-9.4.9.v20180320; built: 2018-03-20T17:51:10+05:30; git: 1f8159b1e4a42d3f79997021ea1609f2fbac6de5; jvm 1.8.0_20-ea-b05
2018-05-05 19:55:05.284  INFO 3764 --- [           main] org.eclipse.jetty.server.session         : DefaultSessionIdManager workerName=node0
2018-05-05 19:55:05.284  INFO 3764 --- [           main] org.eclipse.jetty.server.session         : No SessionScavenger set, using defaults
2018-05-05 19:55:05.318  INFO 3764 --- [           main] org.eclipse.jetty.server.session         : Scavenging every 660000ms
2018-05-05 19:55:05.356  INFO 3764 --- [           main] o.e.j.s.h.ContextHandler.application     : Initializing Spring embedded WebApplicationContext
2018-05-05 19:55:05.356  INFO 3764 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1745 ms
2018-05-05 19:55:05.500  INFO 3764 --- [           main] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-05-05 19:55:05.503  INFO 3764 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-05-05 19:55:05.503  INFO 3764 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-05-05 19:55:05.503  INFO 3764 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-05-05 19:55:05.503  INFO 3764 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-05-05 19:55:05.507  INFO 3764 --- [           main] o.e.jetty.server.handler.ContextHandler  : Started [email protected]{/,[file:///C:/Users/user/AppData/Local/Temp/jetty-docbase.8385296376636463789.8080/],AVAILABLE}
2018-05-05 19:55:05.508  INFO 3764 --- [           main] org.eclipse.jetty.server.Server          : Started @3044ms
2018-05-05 19:55:05.631  INFO 3764 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-05 19:55:05.934  INFO 3764 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.ser[email protected]e136d3: startup date [Sat May 05 19:55:03 IST 2018]; root of context hierarchy
2018-05-05 19:55:06.021  INFO 3764 --- [           main] 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.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-05-05 19:55:06.023  INFO 3764 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-05-05 19:55:06.050  INFO 3764 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-05 19:55:06.050  INFO 3764 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-05 19:55:06.266  INFO 3764 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-05-05 19:55:06.284  INFO 3764 --- [           main] o.e.j.s.h.ContextHandler.application     : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-05-05 19:55:06.284  INFO 3764 --- [           main] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2018-05-05 19:55:06.297  INFO 3764 --- [           main] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 13 ms
2018-05-05 19:55:06.343  INFO 3764 --- [           main] o.e.jetty.server.AbstractConnector       : Started [email protected]{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2018-05-05 19:55:06.346  INFO 3764 --- [           main] o.s.b.web.embedded.jetty.JettyWebServer  : Jetty started on port(s) 8080 (http/1.1) with context path '/'
2018-05-05 19:55:06.351  INFO 3764 --- [           main] com.springexamples.demo.Application      : Started Application in 3.49 seconds (JVM running for 3.886)
Download Sourcecode
  • 1
  • 2
  • Next Page »

Development Environment

  • Spring Boot 2.0.1.RELEASE
  • Maven
  • JDK 8
  • Eclipse

Spring Boot Tutorial

  • Hello world example
  • Which main class
  • Print all beans
  • Embedded jetty server
  • CommandLineRunner
  • Custom banner
  • Change Root Path and Server Port

Spring Tutorial

  • IoC Container
  • Java Configuration

Spring WebMVC Tutorial

  • Minimum required config

Copyright © 2016 · springexamples.com · All Rights Reserved. | Sitemap