ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
读取配置文件中的信息可以使用注解`@ConfigurationProperties`,或`@Value`。 <br/> 以读取`application.properties`为例,`application.yml`的配置文件也是一样的读取。步骤如下: **1.`application.properties`** ```properties account.config.name=zhangsan account.config.password=123456 ``` **2. 实体类** 使用注解`@ConfigurationProperties`读取: ```java @Data //将当前类注入到IoC容器中 @Component //将会读取application.properties中以account.config为前缀的信息 @ConfigurationProperties(prefix = "account.config") public class AccountProperties { private String name; private String password; } ``` 或使用注解`@Value`读取: ```java @Data @Component public class AccountProperties { @Value("${account.config.name}") private String name; @Value("${account.config.password}") private String password; } ``` **3. 测试** ```java @SpringBootTest class Boot02ApplicationTests { @Autowired private AccountProperties properties; @Test void contextLoads() { System.out.println(properties); //AccountProperties(name=zhangsan, password=123456) } } ```