springboot配置文件(.yml)中自定义属性值并在controller里面获取

1,由于项目需要,学习了新的框架--springboot,顺便练习一下在.yml中配置自定义属性并在controller里面获取。(以下的Springboot框架我已经搭建好,就不在陈述)

2,springboot支持很多外部配置,这里就不多介绍了。说说.properties和.yml文件在springboot中的区别:

优先级:如果在项目中同时配置了.yml和.properties文件,那么会优先加载.properties文件。

作用:在properties中以.进行分割,.yml中以“:”进行分割:,并且它以key-value和“:”进行赋值。

注意的地方:

缩进只能用空格键!!!!只能!!!

每个key的冒号后面一定要加空格!!!

3,以下是.yml文件中的代码:

spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: 123456
server:
port: 8080
servlet:
context-path: /testspringboot
#访问地址:http://localhost:8081/testspringboot/

yybx: #自定义的属性和值
name: yuxi
age : 26

yybx是我简单自定义的两个属性,接下来建立一个bean类:

@Component
public class Testbean
{
@Value("${yybx.name}")
private String name;
@Value("${yybx.age}")
private Integer age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}
}
@Component:将实体类注入到spring中方便以后取出
 @Value("${yybx.name}")
private String name;
@Value("${yybx.age}")
private Integer age;
上面四行是将yybx中的属性取出来对应的赋值给bean中的属性
编写测试类:

控制台:

 取值成功!
还有一种使用@ConfigurationProperties方式取值,感觉没有这种方式简单,这里先不陈述,以后会继续添加!

猜你喜欢

转载自www.cnblogs.com/yuxifly828/p/9707184.html