Using an External Property File

Learn how to use an external property file in the Java application.

Applications have a lot of configuration and keeping it separate from the code leads to clarity. If the property file is inside the jar when the application is built, it can’t be changed later without having to un-compress the jar. Spring provides a way to change configuration while the application jar remains intact.

The application configuration is different in different environments. Local machines are used in development, then the application moves to a test environment, and afterwards a production server is used. To use different configurations in different environments, a property file is used to externalize the values for each environment. For example, the database connection in the data layer might be different in different environments. The developer can create an application with default properties and deploy it. Then, if the values need to be changed, an external property file will do the trick. The values from the external property file outside the jar overwrite the values inside the jar.

application-properties file

The application-properties file is a text file that defines the key-value pair for a property. The name of the property follows a convention where the class name is used with the property name to disambiguate properties with the same name in different classes.

For the code example shown in this lesson, we have created a sub-package called lesson15 inside the package io.datajek.spring.basics.movierecommendersystem. The package contains MovieRecommenderSystemApplication.java, Filter.java, ContentBasedFilter.java, CollaborativeFilter.java, and RecommenderImplementation.java files copied from lesson6 sub-package.

Our movie recommender system has been using a hard coded input string, Finding Dory, for the movie. We can create a variable favoriteMovie in RecommenderImplementation class for the input string as follows:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.