How to fetch data from Properties file in JAVA

How to fetch data from Properties file in JAVA

Hello friends,

In this article we will learn how to fetch properties file data in java project.

In java we are fetching data from properties file. And the files must be inside recourse folder. There are two types

From "application.properties"

If the file name is application.properties,

mongodb.host=test.eastus.cloudapp.azure.com

mongodb.username=user
mongodb.password=pwd
mongodb.database=database1
mongodb.port=27017

Then here is the code to fetch in your Java code.

I created a class to get the data and give Configuration annotation because when spring start running, that time it will fetch data from properties file.

Value will contain key of your data;

@Component
@Configuration
public class MongoDbProp {

    @Value("${mongodb.host}")
    private String host;
    @Value("${mongodb.port}")
    private int port;
    @Value("${mongodb.database}")
    private String database;
    @Value("${mongodb.username}")
    private String username;
    @Value("${mongodb.password}")
    private String password;

//with getter and setter
}

From other than application.properties

Suppose you gave the file name as mongodb.properties, then how to fetch in java.

We will use same properties here also.

Lets see how to do in Java.

In classpath give the file name.

@Component
@Configuration
@PropertySource("classpath:mongodb.properties")
@ConfigurationProperties(prefix="mongodb")
public class MongoDbProp {

    private String host;
    private int port;
    private String database;
    private String username;
    private String password;

//use getter and setter
}

Where ever you want this data you can use by creating object with Autowired.

@Autowired
    private MongoDbProp dbProp;

I hope you learn from this article. Thank you :)