Monday, 30 July 2018

Spring boot: Application property files

In this post, you are going to learn
a.   What is 'application.properties' file
b.   Example application using 'application.properties' file
c.   Where can I place 'application.properties' file?
d.   How to change the configuration file name?
e.   How to refer the explicit location of the config file name?

What is 'application.properties' file
You can configure the spring application by placing the properties in 'application.properties' file.

Example application using 'application.properties' file
Create ‘application.properties’ file and place it in application class path. For example, I added this file in src/main/resources folder.

application.properties
vendorName=selflearningjava
version=1.5

By using @Value annotation, you can inject these properties.

ConfigBean.java
package com.sample.myApp.model;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ConfigBean {

 @Value("${vendorName}")
 private String vendor;

 @Value("${version}")
 private String version;

 public String getVendor() {
  return vendor;
 }

 public void setVendor(String vendor) {
  this.vendor = vendor;
 }

 public String getVersion() {
  return version;
 }

 public void setVersion(String version) {
  this.version = version;
 }

}

Application.java

package com.sample.myApp;

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

import com.sample.myApp.model.ConfigBean;

@SpringBootApplication
public class Application {

 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

  ConfigBean configBean = applicationContext.getBean(ConfigBean.class);

  String vendor = configBean.getVendor();
  String version = configBean.getVersion();

  System.out.println("**********************************************");
  System.out.printf("vendor : %s\n", vendor);
  System.out.printf("version : %s\n", version);
  System.out.println("**********************************************");
  
  applicationContext.close();

 }

}


When you ran ‘Application.java’, you can able to see below messages in the console.

**********************************************
vendor : selflearningjava
version : 14.3
**********************************************


Project structure looks like below.


Where can I place 'application.properties' file?
SpringApplication loads properties from application.properties files in the following locations and adds them to the Spring Environment:

a.   A /config subdirectory of the current directory
b.   The current directory
c.   A classpath /config package
d.   The classpath root

The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).

How to change the configuration file name?
If you do not like the configuration file name 'application.properties', then you can change the configuration file name by specifying 'spring.config.name' environment property.

For example, below command checks for the filename 'configuration.properties' instead of 'applicaiton.properties'.
java -jar myproject.jar --spring.config.name=configuration

How to pass the config file name in eclipse?
Right click on ‘Application.java’ -> Run As -> Run Configurations



Add below statement in ‘Arguments’ tab.

--spring.config.name=configuration


How to refer the explicit location of the config file name?
You can also refer to an explicit location by using the spring.config.location environment property.

Example
java -jar myproject.jar --spring.config.location=classpath:/default.properties,

You can specify multiple locations by separating them by comma (,).

Example
java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties




Previous                                                 Next                                                 Home

Sunday, 29 July 2018

Spring boot: RandomValuePropertySource: Working with random values

The RandomValuePropertySource is useful for injecting random values. You can generate random integers, longs, uuids, or strings.

Example
app.secret=${random.value}
app.number=${random.int}
app.bignumber=${random.long}
app.uuid=${random.uuid}
app.number.less.than.fifty=${random.int(50)}
app.number.in.range=${random.int[500,1000]}

You can inject them in java application like below.

@Value("${app.secret}")
private String secret;

@Value("${app.number}")
private int number;

@Value("${app.bignumber}")
private long bigNumber;

@Value("${app.uuid}")
private String uuid;

@Value("${app.number.less.than.fifty}")
private int numberLessThan50;

@Value("${app.number.in.range}")
private int numberInRange;

Find the below working example
application.properties
app.secret=${random.value}
app.number=${random.int}
app.bignumber=${random.long}
app.uuid=${random.uuid}
app.number.less.than.fifty=${random.int(50)}
app.number.in.range=${random.int[500,1000]}

ConfigBean.java
package com.sample.myApp.model;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ConfigBean {

 @Value("${app.secret}")
 private String secret;

 @Value("${app.number}")
 private int number;

 @Value("${app.bignumber}")
 private long bigNumber;

 @Value("${app.uuid}")
 private String uuid;

 @Value("${app.number.less.than.fifty}")
 private int numberLessThan50;

 @Value("${app.number.in.range}")
 private int numberInRange;

 public String getSecret() {
  return secret;
 }

 public void setSecret(String secret) {
  this.secret = secret;
 }

 public int getNumber() {
  return number;
 }

 public void setNumber(int number) {
  this.number = number;
 }

 public long getBigNumber() {
  return bigNumber;
 }

 public void setBigNumber(long bigNumber) {
  this.bigNumber = bigNumber;
 }

 public String getUuid() {
  return uuid;
 }

 public void setUuid(String uuid) {
  this.uuid = uuid;
 }

 public int getNumberLessThan50() {
  return numberLessThan50;
 }

 public void setNumberLessThan50(int numberLessThan50) {
  this.numberLessThan50 = numberLessThan50;
 }

 public int getNumberInRange() {
  return numberInRange;
 }

 public void setNumberInRange(int numberInRange) {
  this.numberInRange = numberInRange;
 }

}

Application.java

package com.sample.myApp;

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

import com.sample.myApp.model.ConfigBean;

import org.springframework.boot.context.config.RandomValuePropertySource;

@SpringBootApplication
public class Application {

 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

  ConfigBean configBean = applicationContext.getBean(ConfigBean.class);
  long bigNumber = configBean.getBigNumber();
  int number = configBean.getNumber();
  int numberInRange = configBean.getNumberInRange();
  int numberLessThan50 = configBean.getNumberLessThan50();
  String secret = configBean.getSecret();
  String uuid = configBean.getUuid();

  System.out.println("******************************");

  System.out.printf("bigNumber : %d \n", bigNumber);
  System.out.printf("number : %d \n", number);
  System.out.printf("numberInRange : %d \n", numberInRange);
  System.out.printf("numberLessThan50 : %d \n", numberLessThan50);
  System.out.printf("secret : %s \n", secret);
  System.out.printf("uuid : %s \n", uuid);

  System.out.println("******************************");

  SpringApplication.exit(applicationContext);
 }

}

When you ran 'Application.java', you can able to see below messages in console.

******************************
bigNumber : -3064097796043813516 
number : -110057729 
numberInRange : 660 
numberLessThan50 : 4 
secret : cc970482bdd5f1f3155019c7016904dc 
uuid : c069726a-c605-4dc4-84a1-761fc02acc59 
******************************






Previous                                                 Next                                                 Home

Saturday, 28 July 2018

Spring boot: Get the port of spring boot application

There are many ways to know about the port that spring boot application is running.
a.   From the log output
b.   From the ServletWebServerApplicationContext through its WebServer
c.   Using ApplicationListener<ServletWebServerInitializedEvent>

From the log output

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) {
  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);
  SpringApplication.exit(applicationContext);
 }

}

Run above application, in the console log, you can able to see below messages.

INFO 2492 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
INFO 2492 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
INFO 2492 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
INFO 2492 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
INFO 2492 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

From the ServletWebServerApplicationContext through its WebServer

ServerDetails.java
package com.sample.myApp.model;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class ServerDetails {
 public ServletWebServerApplicationContext getServer() {
  return server;
 }

 public void setServer(ServletWebServerApplicationContext server) {
  this.server = server;
 }

 @Autowired
 private ServletWebServerApplicationContext server;
 
 
}

Application.java
package com.sample.myApp;

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

import com.sample.myApp.model.ServerDetails;

@SpringBootApplication
public class Application {

 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

  ServerDetails serverDetails = applicationContext.getBean(ServerDetails.class);

  int port = serverDetails.getServer().getWebServer().getPort();

  System.out.println("************************************");
  System.out.printf("Web server is running on %d\n", port);
  System.out.println("************************************");
  SpringApplication.exit(applicationContext);
 }

}


When you ran Application.java, you can able to see below messages in console.
************************************
Web server is running on 8080
************************************

Using ApplicationListener<ServletWebServerInitializedEvent>

PortListener.java
package com.sample.myApp.listeners;

import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class PortListener implements ApplicationListener<ServletWebServerInitializedEvent> {

 @Override
 public void onApplicationEvent(final ServletWebServerInitializedEvent event) {
  int port = event.getWebServer().getPort();

  System.out.println("************************************");
  System.out.printf("Web server is running on %d\n", port);
  System.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) {
  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

  SpringApplication.exit(applicationContext);
 }

}

When you ran Application.java, you can able to see below messages in console.

************************************
Web server is running on 8080

************************************









Previous                                                 Next                                                 Home

Spring boot: mapping exit codes and exceptions

ExitCodeExceptionMapper is a strategy interface, that can be used to provide a mapping between exceptions and exit codes.

Example
         @Bean
         ExitCodeExceptionMapper exitCodeExceptionMapper() {
                  return exception -> {

                           if (exception.getCause() instanceof CustomSpringBootException) {
                                    System.out.println("I am in Exception mapper");
                                    return 10;
                           } else if (exception.getCause() instanceof ArrayIndexOutOfBoundsException) {
                                    return 11;
                           }
                           return 1;
                  };
         }

Find the below working application.

CustomSpringBootException.java
package com.sample.myApp.exceptions;

public class CustomSpringBootException extends RuntimeException {

 private static final long serialVersionUID = 1L;

 public CustomSpringBootException(String message) {
  super(message);
 }

}

MyCommandLineRunner.java
package com.sample.myApp.runners;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.sample.myApp.exceptions.CustomSpringBootException;;

@Component
public class MyCommandLineRunner implements CommandLineRunner {

 @Override
 public void run(String... args) throws Exception {

  System.out.println("************************");
  System.out.println("Inside \"MyCommandLineRunner\" and going to throw \"CustomSpringBootException\"");
  System.out.println("************************");

  throw new CustomSpringBootException("Exception thrown from \"MyCommandLineRunner\"");
 }

}

Application.java
package com.sample.myApp;

import org.springframework.boot.ExitCodeEvent;
import org.springframework.boot.ExitCodeExceptionMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;

import com.sample.myApp.exceptions.CustomSpringBootException;

@SpringBootApplication
public class Application {

 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

  System.out.println("Closing Application Context");

  int exitCode = SpringApplication.exit(applicationContext);

  System.out.printf("Application Context is exited with : %d", exitCode);

 }

 @Bean
 ExitCodeExceptionMapper exitCodeExceptionMapper() {
  return exception -> {

   if (exception.getCause() instanceof CustomSpringBootException) {
    System.out.println("I am in Exception mapper");
    return 10;
   } else if (exception.getCause() instanceof ArrayIndexOutOfBoundsException) {
    return 11;
   }
   return 1;
  };
 }

 @Bean
 public ExitCodeEventModel exitCodeEventModelIntance() {
  return new ExitCodeEventModel();
 }

 private static class ExitCodeEventModel {

  public ExitCodeEventModel() {
   System.out.println("Instantiating ExitCodeEventModel object");
  }

  @EventListener
  public void exitCodeEvent(ExitCodeEvent event) {
   System.out.println("*************************************");
   System.out.println("exit code: " + event.getExitCode());
   System.out.println("*************************************");
  }
 }
} 


Output
************************
Inside "MyCommandLineRunner" and going to throw "CustomSpringBootException"
************************
I am in Exception mapper
*************************************
exit code: 10
*************************************

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-05-14 08:20:52.940 ERROR 10824 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
 at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:800) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
 at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:781) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
 at org.springframework.boot.SpringApplication.run(SpringApplication.java:335) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
 at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
 at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
 at com.sample.myApp.Application.main(Application.java:17) [classes/:na]
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
 at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_161]
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_161]
 at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_161]
 at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.0.1.RELEASE.jar:2.0.1.RELEASE]
Caused by: com.sample.myApp.exceptions.CustomSpringBootException: Exception thrown from "MyCommandLineRunner"
 at com.sample.myApp.runners.MyCommandLineRunner.run(MyCommandLineRunner.java:18) ~[classes/:na]
 at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:797) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
 ... 10 common frames omitted

Project structure looks like below.







Previous                                                 Next                                                 Home