Properties in Spring Boot

Introduction to the

In this article we will discuss how to use Properties in Spring Boot. Properties can be used in two ways, either as annotations of Java code or as configuration of XML files. This article will focus on annotations of Java code.

Register a Properties file with annotations

To register the Properties file we can use the @propertysource annotation, which needs to be used in conjunction with @Configuration.

@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {
    / /...
}
Copy the code

We can also use placeholder to dynamically select properties files:

@PropertySource({ 
  "classpath:persistence-${envTarget:mysql}.properties"
})
Copy the code

@propertysource can also be used multiple times to define multiple property files:

@PropertySource("classpath:foo.properties")
@PropertySource("classpath:bar.properties")
public class PropertiesWithJavaConfig {
    / /...
}
Copy the code

We can also use @propertysources to contain multiple @propertysource:

@PropertySources({
    @PropertySource("classpath:foo.properties"),
    @PropertySource("classpath:bar.properties")})public class PropertiesWithJavaConfig {
    / /...
}
Copy the code

Using properties files

The simplest and most straightforward way to use it is with the @value annotation:

@Value( "${jdbc.url}" )
private String jdbcUrl;
Copy the code

We can also add default values to properties:

@Value( "${jdbc.url:aDefaultUrl}" )
private String jdbcUrl;
Copy the code

If we want to use attribute values in our code, we can get them from the Environment API:

@Autowired
privateEnvironment env; . dataSource.setUrl(env.getProperty("jdbc.url"));
Copy the code

Properties file in Spring Boot

By default, Spring Boot reads the application.properties file as the default properties file. Of course, we can also provide a different properties file on the command line:

java -jar app.jar --spring.config.location=classpath:/another-location.properties
Copy the code

If in a test environment, we can specify the properties file for the test using @testpropertysource:

@RunWith(SpringRunner.class)
@TestPropertySource("/foo.properties")
public class FilePropertyInjectionUnitTest {
 
    @Value("${foo}")
    private String foo;
 
    @Test
    public void whenFilePropertyProvided_thenProperlyInjected(a) {
        assertThat(foo).isEqualTo("bar"); }}Copy the code

In addition to the properties file, we can also directly use the form key=value:

@RunWith(SpringRunner.class)
@TestPropertySource(properties = {"foo=bar"})
public class PropertyInjectionUnitTest {
 
    @Value("${foo}")
    private String foo;
 
    @Test
    public void whenPropertyProvided_thenProperlyInjected(a) {
        assertThat(foo).isEqualTo("bar"); }}Copy the code

Using @SpringBoottest, we can also use a similar function:

@RunWith(SpringRunner.class)
@SpringBootTest(properties = {"foo=bar"}, classes = SpringBootPropertiesTestApplication.class)
public class SpringBootPropertyInjectionIntegrationTest {
 
    @Value("${foo}")
    private String foo;
 
    @Test
    public void whenSpringBootPropertyProvided_thenProperlyInjected(a) {
        assertThat(foo).isEqualTo("bar"); }}Copy the code

@ConfigurationProperties

If we have a set of properties that we want to encapsulate as a bean, we can consider using @ConfigurationProperties.

@ConfigurationProperties(prefix = "database")
public class Database {
    String url;
    String username;
    String password;
 
    // standard getters and setters
}
Copy the code

The properties file is as follows:

database.url=jdbc:postgresql:/localhost:5432/instance
database.username=foo
database.password=bar
Copy the code

Spring Boot will automatically map these properties files to Java bean properties, so all we need to do is define a prefix.

Yaml files

Spring Boot also supports yamL files, which are friendlier and more convenient for hierarchical properties. Take a look at the comparison between the properties files and YAML files:

database.url=jdbc:postgresql:/localhost:5432/instance
database.username=foo
database.password=bar
secret: foo
Copy the code
database:
  url: jdbc:postgresql:/localhost:5432/instance
  username: foo
  password: bar
secret: foo
Copy the code

Note that yamL files cannot be used in @propertysource. If you use @propertysource, you must specify the properties file.

Properties environment variable

We can pass the property environment variable as follows:

java -jar app.jar --property="value"
Copy the code

~~shell java -Dproperty.name=”value” -jar app.jar

Or this: ~~~shellexport name=value
java -jar app.jar
Copy the code

What’s the use of environment variables? When specific environment variables are specified, Spring Boot will automatically load the application-environment.properties file, and the default Spring Boot properties file will also be loaded, but with a lower priority.

Java Code Configuration

In addition to the annotation and the default properties files, Java can also use PropertySourcesPlaceholderConfigurer to loading shown in code:

@Bean
public static PropertySourcesPlaceholderConfigurer properties(a){
    PropertySourcesPlaceholderConfigurer pspc
      = new PropertySourcesPlaceholderConfigurer();
    Resource[] resources = new ClassPathResource[ ]
      { new ClassPathResource( "foo.properties")}; pspc.setLocations( resources ); pspc.setIgnoreUnresolvablePlaceholders(true );
    return pspc;
}
Copy the code

Examples of this article can be found at: github.com/ddean2009/l…

See flydean’s blog for more tutorials