如何在Spring服务器启动期间处理属性文件中的值?

huangapple go评论44阅读模式
英文:

How to process property file values during server start up in Spring?

问题

我在我的Spring Boot应用的application.properties文件中有这个条目:

myapp.urls = url1,url2,url3

在我的组件的一个方法中,我创建了一个数组,代码如下:

String myArray[] = properties.getmyAppUrls().split(",");

我希望这个数组的创建逻辑只执行一次。我知道我们可以使用@PostConstruct注解来实现这一点。除此之外,有没有其他方法可以在服务器启动时实现这个逻辑?

我希望在服务器启动期间从属性文件中读取并构造这个数组,并在我的组件中使用它。

英文:

I have this entry in application.properties of my spring boot app:

myapp.urls = url1,url2,url3

In a method in my component, I am creating an array like below:

String myArray[] = properties.getmyAppUrls().split(",");

I want this array creation logic execute only once. I know we can achieve this using post construct. Is there any other way we could achieve this like during server start up?

I want this array constructed reading from a properties file during server start up and i want to use this in my component.

答案1

得分: 0

你可以使用Spring EL来完成这项任务:

@Value("#{'${myapp.urls}'.split(',')}") 
private List<String> myAppUrls;

我建议将这段代码移到一个Configuration类中,然后你可以在需要的地方进行自动装配。

英文:

You can use Spring EL to do the job:

@Value(&quot;#{&#39;${myapp.urls}&#39;.split(&#39;,&#39;)}&quot;) 
private List&lt;String&gt; myAppUrls;

I'd recommend to move this to a Configuration class, then you can autowire it everywhere you need it.

huangapple
  • 本文由 发表于 2023年2月10日 13:38:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75407344.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定