Categories
java spring-boot

read value from application.properties spring boot

In this post, we will learn to read value from application.properties spring boot

In spring boot application we can easily inject the properties value from application.properties or application.yml

Using @value annotation we can inject the properties value from application.properties inside the java code

@value Syntax
@Value("${application.username}")
private String userName;

application.properties
#userName property
application.username=admin

# Add database url here
spring.datasource.url=jdbc:mysql://localhost:3306/beginnersbug
spring.datasource.username=root
spring.datasource.password=password
# Add driver class here 
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

In the below example, we are writing a rest service that will return the properties value from the application.properties

RestController

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class VariableInjectionController {

	@Value("${application.username}")
	private String userName;

	@GetMapping
	public String getUserName() {
		return userName;
	}
}

In the above example, we will return the application. username property via rest service

Default Value

In case of application. username property is not available means, we can set the default value for that property

Default Value Syntax
@Value("${application.name:BegineersBug}")
private String userName;

From the above snippet, it will take userName value as BeginnersBug because we don’t have application.name property in our application.properties

Github Link

https://github.com/rkumar9090/student-service/blob/master/src/main/java/com/beginnersbug/studentservice/controller/VariableInjectionController.java

Related Articles

configure datasource programmatically in spring boot

Leave a Reply

Your email address will not be published. Required fields are marked *