嗨 Spring/SpringBoot/Yaml/Java 专家,我想在 @Value 中注入(inject)属于类 Perm
的值列表
但是,Spring 无法启动我的应用程序并抛出如下错误:
注入(inject) Autowiring 依赖项失败;嵌套异常是 java.lang.IllegalArgumentException:无法解析值“${myservice.api.perms}”中的占位符“myservice.api.perms”
我是 Spring、Spring Boot 和 Yaml 的新手,请您帮助我
# application.yaml file
myservice:
api:
perms:
-
name: xyz
guid: abc
index: 0
// Class file that wants to read a List<Perm> from the application.yaml file
@Slf4j
@Getter
@Service
@Accessors(fluent = true)
public class MyService {
@Value("${myservice.api.perms}")
private List<Perm> perms;
public List<Perm> getListOfPerms() {
return perms;
}
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class Perm {
@NotBlank
private String name;
@NotBlank
private String guid;
private int index;
}
}
最佳答案
您应该使用@ConfigurationProperties
在这种情况下!
@Configuration
@ConfigurationProperties("myservice.api")
@Getter
@Setter
@Validated
public class ApiProperties {
@NestedConfigurationProperty
@NotEmpty
private List<@Valid Perm> perms;
@Getter
@Setter
public static class Perm {
@NotBlank
private String name;
@NotBlank
private String guid;
@NotNull
@Positive
private Integer index;
}
}
更多资源:
- Guide to @ConfigurationProperties in Spring Boot (Baeldung)
- Type-safe Configuration Properties ( Spring 引用)
关于java - 如何在 Spring @Value 中注入(inject)非原始对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75392363/