[英]Mapstruct value from application.properties
Is it possible to set a value from a field from the application.properties file?是否可以从application.properties文件中的字段设置值?
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.其中application.version=v1
来自application.properties文件。
As far as my knowledge goes, this is not possible.至于我的知识去,这是不可能的。 Mapstruct analyses the @Mapping
annotation in compile time. Mapstruct 在编译时分析@Mapping
注解。 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.您总是可以在MapStruct
中实现满足您需求的东西。 But I would go with a simple self-implemented mapper where you take the value from your version
field in runtime from the environment.但是我会使用一个简单的自实现映射器,您可以在运行时从环境中的version
字段中获取值。
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:也可以看看:
This is not possible through MapStruct.这通过 MapStruct 是不可能的。 However, a feature could be raised that would support some custom expression language that would use Spring @Value
and inject that.但是,可以提出一个特性来支持一些使用 Spring @Value
并注入它的自定义表达式语言。
eg例如
@Mapping(target="version", expression="springValue(${application.version})")
StateDto stateToStateDto(State state);
and then MapStruct will generate something like:然后 MapStruct 将生成如下内容:
@Component
public class StateMapperImpl {
@Value("${application.version}")
private String version;
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.