spring hava方法是否通过@Value字符串文字获取字段?

@Value("${properties.name:Tom}")

String name;

@Value("${properties.email}")

String email;

我想通过注释的值获取 Filed。 getField("properties.name") 返回字符串字段名称,而不是值“tom”。spring有这样的方法吗?


元芳怎么了
浏览 103回答 1
1回答

青春有我

可以使用反射,因为Value有 RetentionPolicyRUNTIMEField field = Stream.of(YourClass.class.getFields())     .filter(field -> field.isAnnotationPresent(Value.class))     .filter(field -> field.getAnnotation(Value.class).value().contains("properties.name")) // or compare to whole expression, or use startsWith, or regex... Also think about NPE check     .findFirst()     .orElse( /* HANDLE FIELD NOT PRESENT */);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java