对于我的 Spring Boot 应用程序,我试图使用一个包含properties.topicsin列表的环境变量application.yml(请参阅下面的配置)。
properties:
topics:
- topic-01
- topic-02
- topic-03
Run Code Online (Sandbox Code Playgroud)
我使用配置文件来填充properties bean(参见这个spring文档),如下图
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("properties")
public class ApplicationProperties {
private List<String> topics = new ArrayList<>();
public void setTopics(List<String> topics) {
this.topics = topics;
}
public List<String> getTopics() {
return this.topics;
}
}
Run Code Online (Sandbox Code Playgroud)
通过使用环境变量,我可以在不更改application.yml. 但是,到目前为止我能找到的所有示例仅适用于环境变量仅包含单个值的情况,而不是我的情况下的值集合。
编辑:
为了在@vancleff 发表评论后说清楚,我不需要将环境变量的值保存到application.yml.
另一个编辑:
我认为通过过度简化我的问题,我在脚下开枪。@LppEdd 答案适用于我的问题中给出的示例。但是,如果我需要更复杂的结构而不是简单的字符串主题名称集合,会发生什么情况。例如,像
properties:
topics:
-
name: topic-01
id: id-1
-
name: topic-02
id: id-2
-
name: …Run Code Online (Sandbox Code Playgroud) 我正在尝试映射这个对象
public class Source {
private String value1;
private String value2;
private String value3;
}
Run Code Online (Sandbox Code Playgroud)
进入这个对象
public class Target {
private String targetValue1;
private String targetValue2;
private String targetValue3;
}
Run Code Online (Sandbox Code Playgroud)
这是映射器的定义。
@Mapper
public interface SourceMapper {
void toTarget(Source source, @MappingTarget Target target);
}
Run Code Online (Sandbox Code Playgroud)
我想要实现的目标是仅当字段source为时才将target字段映射到。例如,仅映射到when is 。如果不是,则忽略该字段的映射。targetnullsource.value1target.targetValue1target.targetValue1nullnull
是否可以使用 MapStruct 而无需编写自定义代码?
编辑
我更改了 的字段名称,Target以明确 的名称Target可能/可能不匹配 中的字段名称Source。