Adding properties with the @PropertySource annotation

Jakub Włodarczyk
2 min readNov 20, 2022

--

The annotation

Property source is a place where you keep your configuration properties. Technically, it’s an abstract class that represents a source of name — value pairs. For instance you can keep database connection information in such structure or decide if you want to enable some debug logs. The @PropertySource annotation is a convenient way to add a property source to the Spring Environment. It is used along with the @Configuration annotation so think about the context of a configuration class.

Declare different properties files under src/main/resources and give them meaningful names like database-connection.properties or logs-properties. Property values can have different types like String, Integer, Boolean or Array. Example properties files with some values:

Properties example

Note that the last property (nonExistingStringProperty) is commented out. It will get a fallback (default) value. To use the properties in a configuration class you need to tell Spring where to find them:

Setting @PropertySource

Note that you can also use the @PropertySources annotation (commented out code). Access a property with the @Value annotation:

Accessing properties

Printing out values of the properties

will give the following:

The values

As you can see the default value (defaultValue) is provided for the commented out property nonExistingStringProperty.

--

--