【问题标题】:Spring Boot get list of classes name from properties and load into HashMapSpring Boot 从属性中获取类名列表并加载到 HashMap
【发布时间】:2021-10-13 14:06:49
【问题描述】:

我在 java 项目中工作,我有一个将在 spring retryTemplate 中使用的异常映射。 这是我的地图:

Map<Class<? extends Throwable>, Boolean> exceptionMap = new HashMap<>();

// list exception to trigger retry
exceptionMap.put(IllegalArgumentException.class, true);
exceptionMap.put(TimeoutException.class, true);
exceptionMap.put(RuntimeException.class, true);
exceptionMap.put(TopicAuthorizationException.class, true);
exceptionMap.put(MemberIdRequiredException.class, true);

我的问题是我不知道确切的异常类,所以我想从属性文件动态加载列表。 这是我的财产:

myapp.exception.class=TimeoutException,RuntimeException,TopicAuthorizationException,MemberIdRequiredException

我在我的班级中加载我的财产:

@Value("${myapp.exception.class}")
private String myclassesList;

您知道如何从我的属性中获取值并将每个元素放入我的地图中。

提前致谢。

问候

【问题讨论】:

标签: java spring spring-boot spring-mvc


【解决方案1】:

有效名称应该是(例如 Runtime 和 IllegalArgument ):

java.lang.RuntimeException, java.lang.IllegalArgumentException

然后您可以使用下面的方法将名称转换为类。

private Class<?> getClass(String name) {
        try {
            return Class.forName(name);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

列表名称转地图的方法如下:

List<String> exList = Arrays.asList(RuntimeException.class.getName(), IllegalArgumentException.class.getName());
Map<Class<?>, Boolean> map = exList.stream().map(name -> getClass(name)).filter(e -> !Objects.isNull(e))
                .collect(Collectors.toMap(e -> e, e -> true));

【讨论】:

    猜你喜欢
    • 2020-02-14
    • 2021-03-23
    • 2014-12-21
    • 1970-01-01
    • 2020-07-01
    • 2017-05-18
    • 2017-11-17
    • 2020-06-05
    • 2019-04-16
    相关资源
    最近更新 更多