Home > Software design >  Mapstruct value from application.properties
Mapstruct value from application.properties

Time:11-13

Is it possible to set a value from a field from the application.properties file?

I am looking for something like

    @Mapping(target="version", expression="${application.version}")
    StateDto stateToStateDto(State state);

where application.version=v1 is from the application.properties file.

CodePudding user response:

As far as my knowledge goes, this is not possible. Mapstruct analyses the @Mapping annotation in compile time. And the annotation parameters require constants. So getting them from a file would not be possible.

You can always implement something in MapStruct that fulfills your needs. But I would go with a simple self-implemented mapper where you take the value from your version field in runtime from the environment.

CodePudding user response:

Consider a "util service" like:

@Service
public class ConstantPropertyService {

  @Value("${application.version}"
  private String appVersion;

  // accessors, more properties/stuff..
}

Then you can define your Mapping like:

@Mapper(// ..., ...
   componentModel = "spring")
public abstract class MyMapper {

  @Autowired
  private ConstantPropertyService myService;

  @Mapping(target="version", expression="java(myService.getAppVersion())")
  StateDto stateToStateDto(State state);
  // ...
}

See also:

  • Related