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.
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:
My minimal solution @github
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With