Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read application.properties value inside the constructor in spring boot?

I know Constructors are calling before the auto wiring the variables. But, unfortunately, I want to read the application.properties value inside the constructor?

@Component
public class DESedeEncryption {
  private static final String key = "TEST_KEY";
  public DESedeEncryption() {
    system.out.println(key);
 }
}

DESedeEncryption encrypted = new DESedeEncryption();

For the above class, the object has been created by using a new operator in my project totally 108 places. Now, I want to read that key value from the application.properties. But, I need to change all 108 places by using @Autowired annotation. But, some of the places the object creation written by using "new" operator in entity class files. So, I can't auto wired the object inside the entity class.

Someone, please help me to solve this issue.

like image 804
AMARESH Avatar asked Nov 16 '25 02:11

AMARESH


1 Answers

You can declare a variable inside the Constructor with @Value annotation, where you want call the application.properties variable.

Example class:

  public DESedeEncryption(@Value("${key}") final String key) {
    system.out.println(key);
 }
like image 117
user13503900 Avatar answered Nov 18 '25 15:11

user13503900



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!