0

I want a certain literal dependency of one of my classes to be compulsory. The values of the literals are stored in a .properties file.

I am declaring the literal inside the class as follows:

private String name
@Value("${company.Name}")
@Required
public void setName(String name) {
    this.name = name;
}

When there is no such key-value pair in the properties file, the value injected into the literal is "${company.Name}" instead of null. This renders the @Required annotation useless. How do I impose the requirement of the literal in this situation?

Tabish Mir
  • 717
  • 6
  • 26
  • Put the `@Value` annotation on the field. Not on setter and remove `@Required` it’s not needed. So now if the key is absent in the properties it will throw an exception. Is that what you want? – Sunil Dabburi Dec 06 '19 at 06:52
  • @SunilChakravarthy Tried doing that. No exception thrown. The literal is still given the value "${company.Name}". – Tabish Mir Dec 06 '19 at 07:18
  • The values are received at runtime, if they aren't you have something weird in your configuration. It should prevent from starting the application instead of resolving to the actual value. This means you are processing things differently then you should be doing. – M. Deinum Dec 06 '19 at 10:05
  • Are you using spring boot or just spring. You should configure `PropertySourcesPlaceholderConfigurer` if you are using just spring – Sunil Dabburi Dec 06 '19 at 14:41
  • Check this https://stackoverflow.com/questions/317687/how-can-i-inject-a-property-value-into-a-spring-bean-which-was-configured-using – Sunil Dabburi Dec 06 '19 at 16:07
  • I think this is a possible duplicate of https://stackoverflow.com/questions/15937592/spring-value-is-not-resolving-to-value-from-property-file – Sunil Dabburi Dec 06 '19 at 20:41

0 Answers0