栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring Boot配置中列表的环境变量

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot配置中列表的环境变量

Suggestion, don’t overcomplicate.

Say you want that list as an

Environment
variable. You’d set it using

-Dtopics=topic-01,topic-02,topic-03

You then can recover it using the injected

Environment
Bean, and create a
new
List<String>
Bean

@Bean@Qualifier("topics")List<String> topics(final Environment environment) {    final var topics = environment.getProperty("topics", "");    return Arrays.asList(topics.split(","));}

From now on, that

List
can be
@Autowired
.
You can also consider creating your custom qualifier annotation, maybe
@Topics
.

Then

@Serviceclass TopicService {   @Topics   @Autowired   private List<String> topics;   ...}

Or even

@Serviceclass TopicService {   private final List<String> topics;   TopicService(@Topics final List<String> topics) {      this.topics = topics;   }   ...}

What you could do is use an externalized file.
Pass to the environment parameters the path to that file.

-DtopicsPath=C:/whatever/path/file.json

Than use the

Environment
Bean to recover that path. Read the file content
and ask
Jackson
to deserialize it

You’d also need to create a simple

Topic
class

public class Topic {    public String name;    public String id;}

Which represents an element of this

JSON
array

[    {        "name": "topic-1",        "id": "id-1"    },    {        "name": "topic-2",        "id": "id-2"    }]

@BeanList<Topic> topics(        final Environment environment,        final ObjectMapper objectMapper) throws IOException {    // Get the file path    final var topicsPath = environment.getProperty("topicsPath");    if (topicsPath == null) {        return Collections.emptyList();    }    // Read the file content    final var json = Files.readString(Paths.get(topicsPath));    // Convert the JSON to Java objects    final var topics = objectMapper.readValue(json, Topic[].class);    return Arrays.asList(topics);}



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/371555.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号