Reputation: 99478
I heard that Properties
is legacy in Java.
Is Properties
still used for load configuration of JDBC from a file as in an an old reply?
Without Properties
, how can we do the same? By normal file-read functions and manually parse the files?
You can save you
db.properties
file to an external fixed location, and access it for later to retrieve your connection properties:Properties props = new Properties(); FileInputStream in = new FileInputStream("/external/configuration/dir/db.properties"); props.load(in); in.close(); String driver = props.getProperty("jdbc.driver"); if (driver != null) { Class.forName(driver) ; } String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); Connection con = DriverManager.getConnection(url, username, password);
Then, on every environment you can have a different copy of your database settings, without having to change your application file (JAR, ER, or whatever).
Sample database connection properties file:
# Oracle DB properties #jdbc.driver=oracle.jdbc.driver.OracleDriver #jdbc.url=jdbc:oracle:thin:@localhost:1571:MyDbSID #jdbc.username=root #jdbc.password=admin # MySQL DB properties jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/MyDbName jdbc.username=root jdbc.password=admin
Upvotes: 0
Views: 753
Reputation: 8587
Yes. At least in my organization, many configurations (not just database conf) are still loaded from properties files, which is perfectly normal and working well. I think it's only legacy in the sense that as a container, the Properties
class came out before the introduction of the Java Collections Framework, like Vector
and Hashtable
.
On the other hand, alternatives like YAML
and JSON
are getting more popular. Probably because it's can become repetitive to describe an object with fields in a properties file.
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/MyDbName
jdbc.username=root
jdbc.password=admin
While the same configuration in YAML
would be more concise and readable(?).
jdbc:
driver: "com.mysql.jdbc.Driver"
url: "mysql://localhost:3306/MyDB"
username: "root"
password: ""
Upvotes: 2