简体   繁体   中英

How to add external properties into a java class in my maven project?

I wanted to store some properties in a separate config file and then use those properties in my java class. I tried looking at resources and getting things done but its not working. I just started with maven so I am not sure whether I am looking at the right resources or not. I will tell you in simple words what I am want to do - I want to store some values such as path and some other parameters into a seperate config file and I want to use those values in my java class. How to do it in a maven project? Thanks.

It's not really about maven but rather java itself.

First of all, are those properties changed by the user?
If yes, you have to use a location which is outside of the jar. (so the user can actually modify it)
If no, you can use the standard resource location and retrieve data from the jar itself.

Do you want an hybrid approach?
Create a default configuration file inside the resource, then copy it outside while running the program the first time. At runtime, If it exists outside, you will use the one provided by the user otherwise the default one which is inside your jar.

How do you handle a configuration file?
You can do it in several way:

  1. Create a simple class which read() and write() on a plain text file then saves data inside an object
  2. Use a standard notation like json, xml, yaml, csv etc... web is plenty of libraries to handle those.
  3. Use java serialization to export the current internal state of your application and load it as you wish but i do not advise it.

What are you really asking for it's how to read and write from a file.
Maven it's a build system to package your application and has nothing to do with your answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM