简体   繁体   中英

Accessing properties from application.properties in a non Controller class

http://www.javadb.com/using-a-message-handler-to-alter-the-soap-header-in-a-web-service-client

In the above mentioned example we have hard coded TestUser(username) and TestPassword(password) in the message handler class.I want to externalize these values. After some research I was not able to implement @Autowired and @value .Please help me out with this

If your .properties file is saved somewhere on the local hard-drive and it is one of the KPL (Key Project Locations), you can simply do this:

Properties propObj = new Properties ();
FileInputStream fis = new FileInputStream("relative path to your file");
propObj.load(fis);

Once you do this, simply use getProperty() or setProperty() to access/mutate desired properties. There is also another way to use the loadFromXML() method if your choice of file is an xml file. I hope this solves your problem because it sounds like you simply having trouble to load a file regardless of being in a controller class. If I am right, then you will find endless examples online that tells you to do merely what I wrote above :)

When using things like @Autowire remember that you have to annotate before the beginning of the target class with @ContextConfiguration("location_of_file.xml") . Getting the correct relative path may be a bit tricky when specifying an applicationContext file. See here and follow other links to find out more about this.

BTW one thing you have to remember that application properties are somewhat internal to an application and for this reason, they are set in a .properties file outside the source files so that it can be run without changing source code (correct me somebody if I am talking bollocks!). If you are using build automation tools such as Maven or Ivy, there is a way to make sure that your application properties are set using the a) POM and b) applicationContext.xml files. In this way, the application is even more decoupled from breaking down in case a relative path doesn't work out to be the some on a target computer. If you want this, you have to be careful about setting the filters in POM. I haven't personally done this by hand, but we were working on a project a few months ago when a colleague of mine set the filer in front of me. I remember this because everything was failing due to incorrect filter setting. Sorry, but you have to find it out yourself using uncle Google!

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