Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapstruct value from application.properties

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.

like image 966
Scala Avatar asked Aug 31 '26 02:08

Scala


2 Answers

Consider a "util service" like:

@Service
public class PropertyService {

  @org.springframework.beans.factory.annotation.Value("${application.version}")
  private String appVersion;

  // accessors, more properties/stuff..
}

Then you can define your Mapping like:

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

  @Autowired
  protected PropertyService myService;

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

See also:

  • Mapstruct - How can I inject a spring dependency in the Generated Mapper class
  • Mapstruct Expressions

My minimal solution @github

like image 58
xerx593 Avatar answered Sep 03 '26 04:09

xerx593


The solution is very simple. You just use abstract class instead of interface, then you can use directly the @Value annotation.

@Mapper(componentModel = "spring")
public abstract class StateMapper {
    @Value("${application.version}")
    protected String applicationVersion;

    @Mapping(target = "version", expression = "java(this.applicationVersion)")
    public abstract StateDto map(State state);
}

This approach is compliant with the official MapStruct documentation:

A mapper could also be defined in the form of an abstract class instead of an interface and implement the custom methods directly in the mapper class. In this case MapStruct will generate an extension of the abstract class with implementations of all abstract methods. An advantage of this approach over declaring default methods is that additional fields could be declared in the mapper class.

like image 35
Honza Zidek Avatar answered Sep 03 '26 03:09

Honza Zidek



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!