第一步:创建一个application.yml文件,内容如下
jdbc:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?characterEncoding=utf-8
username: root
password: 1234
第二步:创建一个配置类获取其中数据
这里使用了三个注解,第一个是将类交给spring管理,第二个表示加载yml中的数据并标明前缀,第三个是lombok插件的注解,提供了get和set方法
@Component
@ConfigurationProperties(prefix = "jdbc")
@Data
public class MyProperties {
private String driverClassName;
private String url;
private String username;
private String password;
}
第三步:测试类进行测试
注意,要再springboot中进行测试要引入几个依赖
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)//表明启动类是哪一个
public class MyPropertiesTest {
@Autowired
private MyProperties myProperties;
@Test
public void test1(){
System.out.println(myProperties);
}
}
引入的依赖
<!--springboot中的测试依赖jar包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>