Reputation: 108
I want to set up some global variables that are accessible by multiple classes. Examples of these global variables would be things like some key(Strings)
I am fetching these variable from database and variables would probably not change except when the program is re-compiled
Upvotes: 2
Views: 15459
Reputation: 30
You can set this properties on application.properties file.You can use this properties all over on your project. For example:I am using key for hit third-party .So I am taking key on my properties file.
Upvotes: 0
Reputation: 1845
You did not provide much details so the answer will be generic too.
There basically are two approaches:
You could use the Java Properties
class.
public static final Properties defaultProperties = new Properties();
Initialize your defaultProperties
from database at program start with defaultProperties.put("name", value)
.
Access your properties by defaultProperties.get("name")
.
Write your own configuration class.
class MyConfig
{
public final String SomeStringProperty;
public final int SomeIntProperty;
// Singleton
public final static MyConfig instance = new MyConfig();
private MyConfig()
{ // Init properties from database here.
}
}
You might need some dependency injection pattern to initialize MyConfig
, e.g. to establish the database connection.
Both methods are similar. The second one provides more type safety and prevents you from accidentally accessing a non existent property because of a typo in the property name. The first one in contrast can be made generic in a way that no code changes to the configuration code are required when new properties are added. Of course, you still have to write code that accesses the new property.
Upvotes: 3
Reputation: 638
The easiest way is to define a @Component
class with field of typeMap
for these properties. Then populate it at the start of your application with information retrieved from database.
Then, whenever you want to use these properties inject these using Spring Boot
's DI mechanism.
Upvotes: 1