无法在spring中绑定application.yml中的对象属性列表



我想将对象属性列表绑定到springbean中的字段,但spring没有绑定。我缺少什么?我的env是SpringBoot v2.7.1+Java 8。

application.yml

application:
mappings:
-   oldname: 'old name 1'
newname: 'new name 1'
-   oldname: 'old name 2'
newname: 'new name 2'

映射属性.java

@ConfigurationProperties(prefix = "application")
public class MappingProperties {
private List<Mapping> mappings;
public List<Mapping> getServers() {
return mappings;
}
public void setServers(List<Mapping> mappings) {
this.mappings = mappings;
}
public class Mapping {
private String oldname;
private String newname;
public String getOldname() {
return oldname;
}
public void setOldname(String oldname) {
this.oldname = oldname;
}
public String getNewname() {
return newname;
}
public void setNewname(String newname) {
this.newname = newname;
}
}
}

DemoApplication.java

@EnableConfigurationProperties(MappingProperties.class)
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
@Autowired
private MappingProperties mappingProperties;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println(mappingProperties);
}
}

看起来您缺少@ConfigurationPropertiesScanhttps://www.baeldung.com/configuration-properties-in-spring-boot

UPD:在这里可以找到一个实现示例:https://www.baeldung.com/spring-boot-yaml-list

我遇到了一个奇怪的困难,很难找到简洁、实用、可工作的例子,所以我想在我把它拼凑起来并使其工作后,我会分享一些代码。

对于某些应用程序。yml如下:

spring:
security:
oauth2:
authorizationserver:
client:
oidc-client:
registration:
client-id: "client ID value"
client-authentication-methods:
- "value 1"
- "value 2"
- "atc."

我创建了一个这样的类:

@Configuration
@ConfigurationPropertiesScan 
@ConfigurationProperties(prefix = "spring.security.oauth2.authorizationserver.client.oidc-client.registration")
public class RewindOidcConfiguration {
private String clientId;
public void setClientId(String value) { this.clientId = value; }
private List<String> clientAuthenticationMethods;
public void setClientAuthenticationMethods(List<String> value) { this.clientAuthenticationMethods = value; }
...
}

这将设置专用字段,然后可供您根据需要使用。这展示了层次结构、名称的灵活绑定、列表值、对setter(Spring调用)的需求等。

相关内容

  • 没有找到相关文章