Mansur
Mansur

Reputation: 1829

How to inject a property from properties file to a non-managed class in Spring?

I would like to set a property to a class that is not managed by Spring. The actual case is as follows: I have a regex which I want to externalize to the properties file. So far what I have tried is to create a CommandLineRunner, and read from properties file and set the regex to whatever field I want. But I wonder if there's an out of the box way to do so.

Upvotes: 1

Views: 470

Answers (1)

Smutje
Smutje

Reputation: 18173

You might do one of the following:

  1. Make the class a "normal" Java class where the regex is passed in via constructor or method parameter by the Spring managed class who uses it.
  2. Give the class a static field "regex" (with a default value perhaps) that gets set by a Spring bean via a setter on startup (@PostConstruct).
  3. Give the class a static field "regex" (with a default value perhaps) that gets set using a static block in your class reading from the properties file (if it is available on the classpath!).
  4. Make the class a "normal" Singleton (with default values perhaps) that gets initialized on Spring startup (https://www.baeldung.com/running-setup-logic-on-startup-in-spring)

Upvotes: 4

Related Questions