Java spring get all properties

Spring Boot Read Values from Application Properties File

In a Spring Boot application, the application.properties (or application.yml ) file is a central place that contains all configurations or settings of the application, in form of key-value pairs. And in this article, I’d love to share with you how to read or bind values of properties in Spring application configuration file in Java code.

1. Bind Property Values to Instance Variables

Spring provides the @Value annotation which can be used to bind value of a property to a field in a Spring component class. Given the following property declared in the application.properties file:

Then you can use @Value(“”) to annotate a member variable (instance field) of a Spring component class, as shown below:

package net.codejava; import org.springframework.beans.factory.annotation.Value; @Service public class ProductService < @Value("$") private Integer pageSize; public Page listAll(int pageNum) < Pageable pageable = PageRequest.of(pageNum - 1, pageSize); return repo.findAll(pageable); >>

Here, when an object of the ProductService class is created, its instance variable pageSize is initialized with the value read from the property named product.page.size which is declared in the application.properties file. It’s easy to use and convenient, right?

Читайте также:  Php перемешать значения массив

If no such property found, a java.lang.IllegalArgumentException will be thrown like this:

java.lang.IllegalArgumentException: Could not resolve placeholder 'product.page.size' in value "$"
@Controller public class AppController < @Value("$") private String defaultPageTitle; . >
@Configuration public class MvcConfig implements WebMvcConfigurer < @Value("") private String productViewName; . >
@Component public class DatabaseLoader < @Value("") private String sampleDatabasePath; . >

Notes:

  • using @Value annotation in a non-Spring class has no effect. It can be used only in @Component , @Service , @Configuration classes
  • You can’t bind property value to a static variable
  • You can’t bind property value to a local variable

2. Bind Property Values to Arguments of Handler Method

@Controller public class AppController < @Autowired private ProductService service; @RequestMapping("/") public String viewHomePage(Model model, @Value("$") String defaultPageTitle) < model.addAttribute("pageTitle", defaultPageTitle); // return view name. >>

In this case, Spring reads property value from application configuration file and pass it as an argument of the handler method when it is invoked. Remember that you can use the @Value annotation in handler method of Spring MVC/REST controller only.

3. Read Properties using Environment object

You can use an Environment object provided by Spring application context to read value of a property from the application configuration file. Below is an example:

import org.springframework.core.env.Environment; @Controller public class AppController < @Autowired Environment env; @RequestMapping("/") public String viewHomePage(Model model) < String pageTitle = env.getProperty("default.page.title"); model.addAttribute("pageTitle", pageTitle); // return view name. >>

As the name implies, you can use Environment object to read system environment variables, for example:

String userHome = env.getProperty("user.dir");

Note that if there are 2 properties with the same name in application configuration file and in system environment variable, the system environment variable will override.

4. Map a set of properties to a JavaBean-style object

Spring framework provides the @ConfigurationProperties annotation which you can use to map a group of properties in the configuration file to a JavaBean object. Suppose that we have some properties sharing the same prefix “myapp” in the application.properties file as below:

myapp.title=Document Upload Lite myapp.version=1.0.0 myapp.build=1234
package net.codejava; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; @ConfigurationProperties(prefix = "myapp") @Configuration("appInfo") public class AppInfo < private String name; private String version; private int build; // getters and setters are not shown for brevity. >
@Controller public class AppController < @Autowired AppInfo appInfo; @RequestMapping("/") public String viewHomePage(Model model) < System.out.println("App name: " + appInfo.getName()); System.out.println("App version: " + appInfo.getVersion()); System.out.println("App build number: " + appInfo.getBuild()); // return view name. >>

You see, it’s very convenient, isn’t it? You can easily map properties from application configuration file to JavaBean object.

5. Read Property Values in Thymeleaf template

In Thymeleaf view template, you can read value of a property using @environment object using the following syntax:

So far in this article, you have learned several ways of reading properties values from Spring application configuration file. I hope you found it helpful. To see the coding in action, watch the following video:

Other Spring Boot Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

Comments

Hi Narendra,
Sorry that course is discontinued. I offer you choosing one of my courses on Udemy here: www.udemy.com/user/namhaminh/

Thanks Nam for the detailed tutorial.I have been following you since 2019.Felt best java tutorials on the internet.
One Question : I had opted for Java email course in 2019.I have got few emails but not all. Have u stopped this course or some other reason.
Please let me know, waiting for your reply!!

CodeJava.net shares Java tutorials, code examples and sample projects for programmers at all levels.
CodeJava.net is created and managed by Nam Ha Minh — a passionate programmer.

Copyright © 2012 — 2023 CodeJava.net, all rights reserved.

Источник

How to display all configuration properties on Spring Boot application startup?

2. The org.springframework.core.env.Environment interface

In Spring Boot applications the Environment is an interface representing the environment in which the current application is running.

We can use that interface to get active profiles and properties of the application environment.

The following code will print all properties from the environment:

package com.frontbackend.springboot; import java.util.Arrays; import java.util.stream.StreamSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.core.env.AbstractEnvironment; import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.Environment; import org.springframework.core.env.MutablePropertySources; @SpringBootApplication public class GettingStartedApplication < private static final Logger LOGGER = LoggerFactory.getLogger(GettingStartedApplication.class); public static void main(String[] args) < SpringApplication.run(GettingStartedApplication.class, args); >@EventListener public void handleContextRefresh(ContextRefreshedEvent event) < final Environment env = event.getApplicationContext() .getEnvironment(); LOGGER.info("Active profiles: <>", Arrays.toString(env.getActiveProfiles())); final MutablePropertySources sources = ((AbstractEnvironment) env).getPropertySources(); StreamSupport.stream(sources.spliterator(), false) .filter(ps -> ps instanceof EnumerablePropertySource) .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()) .flatMap(Arrays::stream) .distinct() .filter(prop -> !(prop.contains("credentials") || prop.contains("password"))) .forEach(prop -> LOGGER.info("<>: <>", prop, env.getProperty(prop))); > > 

Note that the Environment object could be autowired in Spring Boot components just like other Spring beans.

The following code prints several environment properties on startup:

package com.frontbackend.springboot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.core.env.Environment; @SpringBootApplication public class GettingStartedApplication implements CommandLineRunner < private static final Logger logger = LoggerFactory.getLogger(GettingStartedApplication.class); @Autowired private Environment env; @Override public void run(String. args) < logger.info("<>", env.getProperty("file.encoding")); logger.info("<>", env.getProperty("java.io.tmpdir")); logger.info("<>", env.getProperty("os.name")); logger.info("<>", env.getProperty("app.name")); > public static void main(String[] args) < SpringApplication.run(GettingStartedApplication.class, args); >> 

3. Conclusion

In this short article, we presented how to print all the important environment information on Spring Boot startup.

Источник

Оцените статью