There is a class annotated with @ConfigurationProperties. It contains fields that are loaded from a file. This file stores server settings, and I want to use them during validation. For example, if the login length is less than specified in the settings, then throw an exception. The problem is that the controller class sees the fields and allows them to be accessed, and the services and DTO request classes do not see, when referring to the fields, they are all null. I load the file with the settings via the @Autowired annotation.

Maybe in the classes of services and DTO there is some other way to get the config? Or why are the fields visible in the controller, but not in other classes?

    2 answers 2

    Use the @Value annotation in combination with systemProperties (within the Spring Context ):

     @Value("#{systemProperties['priority']}") private String spelValue; 

    or

     @Value("#{systemProperties.myProp}") private String spelValue; 

    Related link: Spring @Value annotation

      The @Autowired works only for bins in context. If you create the instance yourself through new or the deserializer does it for you, the annotations do not work.

      • Hmm, and then what is the way to access the config fields from the DTO classes? I even tried to explicitly pass an object from the controller-> service-> DTO, but when accessing the fields it was still null. - noob1234
      • No (not quite true, you can distort and write monstrokod). That is why it is better to place all the logic in services. There is access to everything. DTOs should not contain any logic ideally. - talex
      • Got it, thanks a lot! Only I and the service do not have access to the config class fields. Access is only available in the controller. - noob1234
      • Add, it is not difficult. Just copy from the controller a field with anotations. - talex
      • Added, does not work. And I can not understand why. - noob1234