简体   繁体   English

Spring RefreshScope 与 SpEL 延迟评估

[英]Spring RefreshScope with SpEL deferred Evaluation

I'm having trouble knowing how this is possible or a potential work around.我无法知道这是如何可能的或潜在的解决方法。 I am looking at configuring variables that are in the form of "foo,bar,baz" into a List as separate elements.我正在考虑将“foo、bar、baz”形式的变量配置为单独的元素到列表中。 Currently the code looks like目前代码看起来像

@RefreshScope
@Configuration
@Getter
public class fakeConfiguration {
    @Value("#{PropertySplitter.toSet('${properties:}')}")
    private final Set<String> field = new HashSet<>();
}   

@Component("PropertySplitter")
@SuppressWarnings("unused")
public class PropertySplitter {
    public Set<String> toSet(String property) {
        Set<String> set = new HashSet<>();

        if(!property.trim().isEmpty()){
            Collections.addAll(set, property.split("\\s*,\\s*"));
        }

        return set;
    }
}

This properly evaluates the String list into a Set however the refreshScope never gets triggered properly.这会正确地将 String 列表评估为 Set,但是 refreshScope 永远不会被正确触发。 If I use如果我使用

    @Value("${properties:}")
    private final String fieldAsString;

I can see the field properly refresh, but I'd like to actively convert the value to a list as it is changed.我可以看到该字段正确刷新,但我想在更改时主动将值转换为列表。 Is this possible?这可能吗?

  1. In newer version of spring-boot below works for application.properties and Application.yml在较新版本的 spring-boot 中,以下适用于application.propertiesApplication.yml
    @Value("#{${props.list}}")
    private List<String> fieldList;
  1. If you use Application.yml you can arrange the objects如果你使用Application.yml你可以安排对象
    props:
      list:
        - val1
        - val2

and then use in code然后在代码中使用

    @Value("${props.list}")
    private List<String> ymlList

Last, You can try the below as well最后,你也可以试试下面的

    @Value("#{'${props.list}'.split(',')}") 
    private List<String> myList;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM