application.properties 中的 Mapstruct 值

Sca*_*ala 6 java spring properties mapper mapstruct

是否可以从application.properties文件中的字段设置值?

我正在寻找类似的东西

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

其中application.version=v1来自application.properties文件。

xer*_*593 6

考虑一个“util 服务”,例如:

@Service
public class PropertyService {

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

  // accessors, more properties/stuff..
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样定义你的映射:

@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);
  // ...
}
Run Code Online (Sandbox Code Playgroud)

也可以看看:


我的最小解决方案@github


Ren*_*235 2

据我所知,这是不可能的。@MappingMapstruct在编译时分析注释。并且注释参数需要常量。因此从文件中获取它们是不可能的。

您始终可以实施一些MapStruct可以满足您需求的东西。但我会使用一个简单的自行实现的映射器,您可以在version运行时从环境中获取字段的值。

编辑:

这个有可能。看到这个答案