💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
如果想在代码中读取配置文件里面的信息,可以调用注解`@Value`、或`@ConfigurationProperties`。 [TOC] # 1. `@Value`读取 **1.`application.yml`** ```yml account: config: username: Zhangsan password: 123456 ``` <br/> **2. 调用`@Value`读取配置** ```java @Slf4j @SpringBootTest class ConfigApplicationTests { @Value("${account.config.username}") private String username; @Value("${account.config.password}") private String password; @Test public void configValue() { log.info("[configValue|username]: {}", username); log.info("[configValue|password]: {}", password); //[configValue|username]: Zhangsan //[configValue|password]: 123456 } } ``` <br/> # 2. `@ConfigurationProperties`读取 **1. `application.yml`** ```yml account: config: username: Zhangsan password: 123456 ``` <br/> **2. 在实体类标注注解`@ConfigurationProperties`** ```java @Data @Component //prefix: 指定要读取的配置的前缀 @ConfigurationProperties(prefix = "account.config") public class AccountPropeties { /** * 与 application.yml 中的配置名保持一致 */ private String username; private String password; } ``` <br/> **3. 测试** ```java @Slf4j @SpringBootTest class ConfigApplicationTests { @Autowired private AccountPropeties accountPropeties; @Test public void configProperties() { log.info("[configProperties|username]: {}", accountPropeties.getUsername()); log.info("[configProperties|password]: {}", accountPropeties.getPassword()); //[configProperties|username]: Zhangsan //[configProperties|password]: 123456 } } ```