Correct approach to Properties

I am working in Java on a fairly large project. My question is about how to best structure the set of Properties for my application.

Approach 1: Have some static Properties object that's accessible by every class. (Disadvantages: then, some classes lose their generality should they be taken out of the context of the application; they also require explicit calls to some static object that is located in a different class and may in the future disappear; it just doesn't feel right, am I wrong?)

Approach 2: Have the Properties be instantiated by the main class and handed down to the other application classes. (Disadvantages: you end up passing a pointer to the Properties object to almost every class and it seems to become very redundant and cumbersome; I don't like it.)

Any suggestions?

Asked by: Aida177 | Posted: 28-01-2022

Answer 1

I like using Spring dependency injection for many of the properties. You can treat your application like building blocks and inject the properties directly into the component that needs them. This preserves (encourages) encapsulation. Then, you assemble your components together and create the "main class".

A nice side effect of the dependency injection is that your code should be more easily testable.

Answered by: Lucas527 | Posted: 01-03-2022

Answer 2

Actually, approach 2 works really well.

I tried using a Singleton properties object on a recent project. Then, when it came time to add features, I need to revise the Singleton, and regretted having to locate every place where I used MySingleton.getInstance().

Approach 2 of passing a global information object through your various constructors is easier to control.

Using an explicit setter helps, too.

class MyConfig extends Properties {...}

class SomeClass {
    MyConfig theConfig;
    public void setConfi( MyConfig c ) {
        theConfig= c;

It works well, and you'll be happy that you tightly controlled precisely which classes actually need configuration information.

Answered by: Lana679 | Posted: 01-03-2022

Answer 3

If the properties are needed by a lot of classes, I would go for approach 1. Or perhaps a variant in which you use the Singleton design pattern instead of all static methods. This means that you don't have to keep passing some properties object around. On the other hand, if only a few classes need these properties, you might choose approach 2, for the reasons you mentioned. You might also want to ask yourself how likely it is that the classes you write are actually going to be reused and if so, how much of a problem it is to also reuse the properties object. If reuse is not likely, don't bother with it now and choose the solution that is the simplest for the current situation.

Answered by: Thomas238 | Posted: 01-03-2022

Answer 4

Sounds like you need a configuration manager component. It would be found via some sort of service locator, which could be as simple as ConfigurationManagerClass.instance(). This would encapsulate all that fun. Or you could use a dependency injection framework like Spring.

Much depends on how components find each other in your architecture. If your other components are being passed around as references, do that. Just be consistent.

Answered by: Walter588 | Posted: 01-03-2022

Answer 5

If you are looking for something quick you can use the System properties, they are available to all classes. You can store a String value or if you need to store a list of 'stuff' you can use the System.Properties() method. This returns a 'Properties' object which is a HashTable. You can then store what ever you want into the table. It's not pretty but it's a quick way to have global properties. YMMV

Answered by: Darcy342 | Posted: 01-03-2022

Answer 6

I usually go for a singleton object that resides in a common project and contains a hashtable of itself keyed on namespace, resulting in a properties class for each.

Dependency injection is also a nice way of doing it.

Answered by: Emily300 | Posted: 01-03-2022

Answer 7

I feel more comfortable when I have a static pointer to my in-memory properties. some times you want to reload properties in runtime, or other functionality that is easier to implement with a static reference.

just remember that no class is an island. a reusable class can have a client class to keep the core free of the singletone reference.

you can also use interfaces, just try not to overdo it.

Answered by: Elise833 | Posted: 01-03-2022

Answer 8

Approache 2 is defenetly better.

Anyway, you should not let other class search through config object. You should injet config taken in the config object ouside the object.

Take a look at apache commons configuration for help with configuration Impl.

So in the main() you could have

MyObject mobj = new MyObject();

Instead of

MyObject mobj = new MyObject();

where appConfig is a wrapper around the apache configuration library that do all the lookup of the value base on the name of the value in a config file.

this way your object become very easily testable.

Answered by: Walter217 | Posted: 01-03-2022

Answer 9

Haven't done Java for a while, but can't you just put your properties into the java.lang.System properties? This way you can access the values from everywhere and avoid having a "global" property class.

Answered by: Ryan725 | Posted: 01-03-2022

Similar questions

java - Regarding Better Approach of Handling Properties

I need to read the two of the following attributes of user details through properties file. username and userid. There may be n number of users inside the properties file.The number is not fixed. In this case what is the best practice to handle this requirement using properties file in java. How about using the following approach. Inside the properties file :

java - Any other approach instead of Properties file?

I have an legacy code base , which is built by using ant. I can see lot’s of properties file been used throughout the project, which gives deployment url and other things. I certainly hate this approach. By any chance, we can remove these properties file and inject these values to Java classes at run time? And I see most of the properties files are used in build.xml. Does other build tool handles these ...

java - Spring Boot : approach to have global access to properties loaded from a custom property table

Background : I don't want to hardcode properties in a java constant file, coz every time I want to change to one of the property_value, I have to build and deploy the entire code again. I don't even want to keep them in application.yaml/ file, coz my properties are huge in numbers(100s). So, I have decided to maintain properties in a properties table in oracle DB. I can think of two approaches ...

Simple properties to string conversion in Java

Using Java, I need to encode a Map<String, String> of name value pairs to store into a String, and be able to decode it again. These will be stored in a database column, and will probably usually be short and simple, so the common case should produce a simple nice looking line, but shouldn't corrupt the data, even if it contains unexpected characters, etc. How would you choose to do it such that: ...

properties - How can I get the location of the JDK directory in Java?

Is there an similar property like System.getProperty("java.home") that will return the JDK directory instead of the JRE directory? I've looked and there doesn't seem to be anything for the JDK.

java - Simple way to detect unused properties keys?

Given a set of properties files and list of files which may reference keys in those properties files, what's the easiest way to determine which keys are unused? Example: Given a project with files kermit=Kermit the Frog oscar=Oscar the Grouch papa=Papa Smurf and /WEB-INF/pag...

java - How do I attach properties files to a jar?

I have a project that uses the serial port, and it requires two files to run, the win32.dll file (which is in the java runtime environment bin folder) and the file (which is in the java runtime environment lib folder). When I run the project from eclipse it works, but when I try to build a jar file for distribution, it won't work. I suspect this is because the dll and properties files aren't included ...

java - How to collect spring properties from multiple files for use on a single bean

I haven't gotten my head wrapped around Spring yet, so correct me if this question doesn't make sense... I have a PropertyPlaceholderConfigurer <bean id="rdbmPropertiesPlacholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" lazy-init="false"> <property name="location" value="classpath:/properties/" /> </bean> A...

java - Can I inject properties into a JPA Entity Listener

I could prototype this and see what happens, but I am being lazy. I want to be able to inject an EJB3 into my JPA Entity Listener so that it can access functionality of the EJB during the PrePersist operation. Is that possible? If not... then under JBoss, will the Listener be created once, or once per method invocation? I guess I am trying to understand how lightweight each invocation will be in terms of doing JNDI lookups...

c# - How to handle properties with dynamic defaults

I often have a situation like this when creating simple data objects. I have a property called Label that should have a default based on the Name of the object. So if no label is set then the Name is used otherwise use the set Label. A simple example in C# public class FooBat { public string Name { get; set; } public string Label { get { if (_label == null) return Name; ...

Can anyone help with a java problem regarding date properties?

I basically want to say if the date is unchanged run this alert my date field is set up like this StartDate = new DateField("Start Date ", DateField.DATE); cal1 = Calendar.getInstance(); cal1.set(Calendar.YEAR, 2009); cal1.set(Calendar.MONTH, 3); cal1.set(Calendar.DAY_OF_MONTH, 1); StartDate.setD...

java - How can I run a Maven webapp in Eclipse when I use profiles to populate properties files at build time?

Here is an example profile in my POM: <profiles> <profile> <id>QA</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <jdbc.url>jdbc:mysql://</jdbc.url> <jdbc.username>webapp</jdbc.username> ...

java - VM options in project properties in netbeans

I got a problem with the java heap space while using servlets in netbeans5.0 and got a solution to resolve it too,they asked to change the VM options of run category in the project properties.But,i couldnt find such option in my properties.Please do tell me what to do with this error. This is the picture of my project properties.

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)