How to store an object that can be accessible globally in Spring

Suppose I have a license file that will be loaded during startup. The data in the file will then be stored to a License object. How can I make this object accessible to different components/services, the Spring way?

Upvotes: 1

Views: 517

Answers (3)

Oreste Viron
Oreste Viron

Reputation: 3805

There are multiple solutions to your problem. The easiest way is to do something like this:

@Configuration
public class LicenseConfig {
  @Bean
  public MyLicense getLicense() {
    // Do stuff and return the license object.
  }
}

Then you can @Autowire the MyLicense object.

Upvotes: 2

Babatope.Festus
Babatope.Festus

Reputation: 133

Create Object and mark it with @Configuration. In your application.properties file, add entries for the file.

@Configuration
public class ApplicationLicense {

    @Value("${myapp.license.version}")
    String version;

    @Value("${myapp.license.code}")
    String license;

    @Value("${myapp.license.expiry}")
    String expiry;
}

Upvotes: 0

Michael Kemmerzell
Michael Kemmerzell

Reputation: 5276

If you build up your file as a property file you can access the data easily per @Value.

For example you create a property file with the following kv-pair: value.from.file=TestTest

@Value("${value.from.file}")
private String valueFromFile; // Contains TestTest

Source

Upvotes: 0

Related Questions