将 YAML 文件注入构造函数

问题描述 投票:0回答:1

我有这个 YAML 文件

src/main/resources/foo.yml
:

bar:
  - hello
  - world
baz:
  - lorem
  - ipsum

这个组件:

@Component
public class MyComponent {
    public MyComponent(Map<String, List<String>> foo) {
        // foo.get("bar")
    }
}

使用 Spring Boot 2.7,是否可以将配置按原样(自己的文件,无前缀,无类)注入到构造函数中?

java spring spring-boot
1个回答
0
投票

你可以这样做

@Configuration
public class MyConfiguration {
   @Bean
   public Map<String, Object> foo(@Value("classpath:foo.yaml") Resource yaml) {
      Yaml yaml = new Yaml();
      return yaml.load(yaml.getInputStream());
   }
}
@Component
public class MyComponent {
    public MyComponent(@Qualifier("foo") Map<String, Object> foo) { ... }
}
© www.soinside.com 2019 - 2024. All rights reserved.