Springboot How to Read Configs From Application Properties

In this example, we will demonstrate how to configure a Spring Boot awarding using the application.backdrop file.

1. Introduction

Spring Kick is an application development solution that will automatically configure your Spring awarding for you, helping you go your project upwards and running equally quickly as possible.  It will consider the dependencies in your project and will utilise an opinionated view and default settings to configure the application.

In well-nigh cases, however, you will want to override some of the default settings.  For example, y'all may want to specify the port for your spider web application (the default port is 8080) or you may want to specify the servlet context path.  (The default context path is "/".)  You can employ the awarding.properties file (or application.yml if you prefer) for this purpose. Jump Kicking will load the file at startup and look for known properties to configure your application. You tin likewise use the application.backdrop file to define custom properties.

In this example, we volition demonstrate how to utilize the awarding.properties file to configure your Bound Boot application.

1.ane Tools Used in this Example

  • Eclipse Java EE IDE for Java Developer 2018-12
  • Jump Tools 4 – for Bound Boot

Jump Tools 4 for Spring Kicking is a set of plugins for Eclipse that support edifice and running Bound Boot applications. You tin can add Spring Tools 4 to your existing Eclipse installation by going to the Eclipse Marketplace and searching for "Spring Tools 4".

ii. Jump Boot Application Properties Instance

2.1 Create the Leap Kick Project

In the New Project – Select a Wizard dialog box, expand Jump Kicking and select Jump Starter Projection. Click "Next".

Spring Boot Application Properties - Select a Wizard
Select a Wizard

In the New Spring Starter Project dialog box, enter a name for the projection. Also, enter the group, artifact and package information. Accept all the other default values. Click "Next".

Spring Boot Application Properties - Spring Boot Project
New Bound Kick Project

In the New Spring Starter Project Dependencies dialog box, select Spring Boot Version 2.1.3. Also, enter "web" in the Available search box and check Spider web from the search results. Click "Finish".

Spring Boot Application Properties - Spring Boot Web Dependency
Leap Boot Web Dependency

2.2 Create the Controller

We'll use a simple Rest controller for this example.  Create a new Java classHelloControllerwith the post-obit code: HelloController.java

import org.springframework.web.bind.note.GetMapping; import org.springframework.web.bind.notation.RestController;  @RestController("/") public class HelloController { 	 	@GetMapping("/howdy") 	public String hello() { 		return "Hello Globe!"; 	}  }        

Allow'due south run and test the application. Right-click your projection in Projection Explorer and select Run As > Bound Boot App. Open up a browser, enter localhost:8080/hullo in the address bar and hit Enter. Notice that we are using the default settings for the server port (8080) and the context path ('/').

Spring Boot Application Properties - Hello World!
Hello Globe!

2.3 Configuration Backdrop

There are over ane,000 configuration properties defined in Jump Boot.  You don't need to set all available backdrop. You only demand to gear up the properties you want to configure in your application.

Properties are grouped into these general categories:

  • Cadre
  • Web
  • Security
  • Data
  • Actuator
  • Integration
  • DevTools
  • Testing

The nearly mutual application properties are documented on Spring'southward official website at https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html.

We'll encompass some of these properties in this article.

ii.four Core Backdrop

The core properties are applicative in most Spring Boot applications.  For example, yous may want to configure the log file for your application.  Right-click application.properties nether src/chief/resource in the Projection Explorer and select Open up with > Generic Editor – Spring Properties.  (If yous don't see this choice, brand certain you lot installed Spring Tools.)

Add together the following property to application.properties: application.properties

# Log file logging.file=logs/my-log-file.log

As you lot type the property proper noun, y'all will notice that the Spring Backdrop editor provides "content-assist". This is a big time-saver every bit you do not take to consult the online documentation for holding names, data types, etc.  (Note: Yous may have to hit Control + spacebar to invoke content-assist.)

Spring Boot Application Properties - Content Assist
Content Assist

If you scroll through the properties, you lot will see their data type, description, and in some cases their default value.  The properties and their attributes are contained in the configuration metadata for Leap Boot.  In the Project Explorer aggrandize Maven Dependencies > leap-boot-ii.one.3.RELEASE.jar > META-INF.  In the META-INF binder, y'all volition see ii JSON files.

  • leap-configuration-metadata.json
  • additional-bound-configuration-metadata.json

Open the spring-configuration-metadata.json file and search for logging.file.  Y'all will see the metadata for the property. spring-configuration-metadata.json

          {       "name": "logging.file",       "type": "java.lang.String",       "description": "Log file name (for instance, `myapp.log`). Names can be an exact location or relative to the current directory.",       "sourceType": "org.springframework.boot.context.logging.LoggingApplicationListener"     }        

Property attributes include the name (required), and optionally, type, clarification, sourceType, defaultValue and deprecated.  (For more data on configuration metadata, visit the Spring Kick documentation at https://docs.spring.io/spring-boot/docs/current/reference/html/configuration-metadata.html)

Save the application.backdrop file.  Now offset or restart the awarding.  Bound Boot will bootstrap the application, load the application.properties file and configure the log file. If you lot refresh the project, y'all will come across that my-log-file.log has been created under the logs folder.

Another useful core property is jump.profiles.active, which is used to specify the Jump contour(due south) to load during startup.  This holding is only applicative if you accept configured profiles in your awarding.  For more information on Spring profiles, view the documentation at https://docs.spring.io/spring-boot/docs/electric current/reference/html/boot-features-profiles.html.

2.v Spider web Backdrop

The embedded server tin can be configured using web properties.  For example, you can specify the port on which your server will listen for requests.  You can likewise specify the servlet context path for your awarding.  Add the following properties to application.backdrop: application.properties

# Server port server.port=9080  # Servlet context path server.servlet.context-path=/helloworld        

When you restart your application, yous will see the following line in the console: Panel Output

Tomcat started on port(s): 9080 (http) with context path '/helloworld'        

Open a browser and use the following URL to ship a request: http://localhost:9080/helloworld/how-do-you-do.

Spring Boot Application Properties - Hello World!
Hello World!

Spring Boot automatically casts string values from the application.backdrop file to the appropriate data type.  For example, the server.port value volition be converted to an integer.

2.6 Custom Backdrop

Yous tin can define your ain custom properties in the application.properties file. Let's look at an example.

Add the following property to the properties file: application.properties

# Custom property person.proper noun=Java Code Geeks!        

Y'all can use the @Value notation and a property identify holder (${…}) to inject the value into your bean. Modify the controller class with the following code: HelloController.java

import org.springframework.beans.mill.annotation.Value; import org.springframework.spider web.bind.annotation.GetMapping; import org.springframework.web.bind.note.RestController;  @RestController("/") public course HelloController { 	 	@Value("${person.proper noun}") 	private String proper noun; 	 	@GetMapping("/hello") 	public String hello() { 		return "Hello " + name; 	} }        

Note: Brand sure the key in the property place holder matches the primal in application.backdrop.  If you mistype and the primal is non constitute, Spring will throw an IllegalArgumentException when trying to create the bean.

Restart the awarding and reload the page.  You will see that the value from the custom property is used in the response.

Spring Boot Application Properties
Hello Java Code Geeks!

2.seven Creating Metadata for Backdrop

You may have noticed that there is a warning for the custom property – person.proper name is an unknown belongings.  You can gear up this past creating metadata for that property.

Gear up your cursor after person.proper name and hit Control + i (or Command +1 on macOS).  Select Create metadata for person.name and hit enter.

Spring Boot Application Properties - Creating Metadata
Creating Metadata for a Custom Property

This will create a file additional-leap-configuration-metadata.json under the META-INF folder in your project.  Open the file with the JSON editor and edit the description. boosted-spring-configuration-metadata.json

{"backdrop": [{   "name": "person.proper name",   "type": "coffee.lang.String",   "description": "The person'due south name to display." }]}        

Now hover over the holding.  Yous will see the information for the property including the updated description.

Spring Boot Application Properties - A Custom Property
A Custom Property

Y'all can add as many custom backdrop and their supporting metadata to the JSON file.  This is a great mode to share custom backdrop with other members of your team.

2.eight Organizing Custom Properties

It tin can be cumbersome to use the @Value notation if you accept many custom properties in your application. If the properties are related, you can organize them using a prefix.  Define the following additional custom properties in awarding.properties: application.properties

# Custom belongings person.name=Java Code Geeks! person.age=25 person.title=Mr.        

Nosotros are using "person" as the prefix to group these properties.  This allows us to treat these properties equally attributes of a single data construction.  Create a POJO "Person" with the following code. Person.java

import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.note.Configuration;  @Configuration @ConfigurationProperties(prefix="person") public class Person { 	 	String name; 	int historic period; 	String title; 	 	public String getName() { 		return name; 	} 	public void setName(String name) { 		this.name = proper name; 	} 	public int getAge() { 		return age; 	} 	public void setAge(int historic period) { 		this.age = historic period; 	} 	public String getTitle() { 		return title; 	} 	public void setTitle(String title) { 		this.championship = title; 	}  }        

The @Configuration annotation registers this POJO as a bean.  The @ConfigurationProperties notation allows u.s.a. to bind this POJO to properties of an external properties file, e.thou. application.properties.  Notice that we are using the prefix "person" to filter the backdrop.

At this indicate, you will see a alarm if yous hover over the @ConfigurationProperties annotation – "When using @ConfigurationProperties information technology is recommended to add 'spring-boot-configuration-processor' to your classpath to generate configuration metadata". Click on the quick set to add together the spring-boot-configuration-processor dependency to the pom.xml.

Spring Boot Application Properties - Configuration Properties Warning
Configuration Properties Warning

Since this POJO is registered as a bean in the application context, nosotros can autowire information technology in the controller class in club to access its properties.  Modify the controller course with the following: HelloController.java

import javax.notation.PostConstruct;  import org.springframework.beans.manufacturing plant.notation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.spider web.bind.annotation.RestController;  @RestController("/") public class HelloController { 	 	@Value("${person.name}") 	individual String name; 	 	@Autowired 	private Person person; 	 	@GetMapping("/hullo") 	public String hullo() { 		return "Hello " + name; 	}  	@PostConstruct 	individual void printPerson() { 		System.out.println("name: " + person.name); 		System.out.println("age: " + person.age); 		Organisation.out.println("title: " + person.championship); 	} }        

Restart the awarding.  You will see the following output in the console:

2019-03-14 22:thirteen:15.385  INFO 6146 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1115 ms name: Coffee Code Geeks! age: 25 title: Mr. 2019-03-fourteen 22:13:15.622  INFO 6146 --- [           main] o.southward.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor' 2019-03-fourteen 22:13:15.832  INFO 6146 --- [           main] o.s.b.due west.embedded.tomcat.TomcatWebServer  : Tomcat started on port(south): 9080 (http) with context path '/helloworld' 2019-03-14 22:thirteen:fifteen.836  INFO 6146 --- [           main] c.j.examples.HelloWorldApplication       : Started HelloWorldApplication in ane.962 seconds (JVM running for 4.612)        

The @ConfigurationProperties annotation provides a more manageable ways of working with related properties.  It as well allows for a centralized mode to validate properties just that is beyond the telescopic of this article.

three. Summary

In this example, we looked as some of the mutual Spring Kick application properties and showed how they are used.  Nosotros also demonstrated how to create your own custom backdrop and how to use them in your application.

iv. Download the Source Code

This was a Leap Kick Application Properties Example

morrisonupeopt.blogspot.com

Source: https://examples.javacodegeeks.com/enterprise-java/spring/boot/spring-boot-application-properties-example/

0 Response to "Springboot How to Read Configs From Application Properties"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel