mardi 24 septembre 2019

How to access Configuration objects in Spring Boot

Spring Boot has a mechanism for accessing the contents of .properties (or YAML) files that one might want to include in an application. I currently have a dbase.properties file (residing in src/main/resources) that contains the following information:

app.dbase.name=MyDbase
app.dbase.connect=jdbc:postgresql://localhost:5432
app.dbase.user=auser
app.dbase.password=mypassword

As described in various Spring Boot documents and examples, I have a configuration class that is defined below:

@Configuration
@PropertySource("dbase.properties")
@ConfigurationProperties(prefix = "app.dbase")
public class DbInfo
{
   private String name;
   private String connect;
   private String user;
   private String password;

   // Getters and setters left out for brevity
}

Unfortunately, while the various documents and examples give good information on how to define a configuration class, I have been unable to find any description on how to use it! Apparently, a Spring Boot web application creates an instance of a configuration class upon startup (and it looks like it also initializes them with the values from the properties file) but my attempts to guess how to access its contents when I need to have failed. The method of doing so is probably simple, but no one seems to want to describe this method anywhere.

So: how does one access and use one of these configuration classes once they are instantiated?




Aucun commentaire:

Enregistrer un commentaire