Kita boleh menggunakan anotasi @Value pada sifat kacang untuk membaca secara langsung nilai dalam yml, seperti. :
application.yml:
name: Zhangsan
Bean:
public class MyBean { @Value("${name}") private String name; }
Kita boleh membaca nilai yml dengan menyuntik objek Environment, seperti:
Configuration@Autowired private Environment environment; public void doSomething() { String name = environment.getProperty("name"); }
application.yml:
my: name: Zhangsan age: 18
Bean:
@Component @ConfigurationProperties(prefix = "my") public class MyProps { private String name; private int age; // getter and setter }
@Bean public static PropertySourcesPlaceholderConfigurer properties() { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(new ClassPathResource("application.yml")); factory.getObject().forEach((k, v) -> System.out.println(k + ": " + v)); return factory; }
application.yml:
my: name: Zhangsan --- my: name: Lisi
@Component("first") @YamlComponent(value = "my.first") public class FirstProps { private String name; } @Component("second") @YamlComponent(value = "my.second") public class SecondProps { private String name; }
Atas ialah kandungan terperinci 3 cara untuk SpringBoot membaca fail yml. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!