2.4 properties文件配置乱码问题
application.properties
#properties的配置文件默认是utf-8编码的,所以需要编码转换
person.age=19
person.birth=2019/12/12
person.boss=false
person.dog.name=dog
person.dog.age=2
person.last-name=张三
person.maps.v1=kd
person.maps.v2=34
执行测试后
中文乱码解决方法:
再次执行:
2.5 @ConfigrationProperties与@Value的区别
@Component
//@ConfigurationProperties(prefix = "person")
@Data
public class Person {
/**
* <bean class = "person">
* <property name= "lastName" value= "字面量/${key}从环境变量、配置文件中获取值/#{SpEl}"</property>
* </bean>
*/
@Value("${person.last-name}")
private String lastName;
@Value("#{11*2}")
private Integer age;
@Value("false")
private Boolean boss;
private Date birth;
private Map<String, Object> maps;
private List<Object> list;
private Dog dog;
}
运行测试:
比较:
@ConfigurationProperties | @Value | |
功能 | 批量注入配置文件中的属性 | 一个个指定 |
松散语法 | 支持 | 不支持 |
SpEl表达式 | 不支持 | 支持 |
JsR303数据校验 | 支持 | 不支持 |
复杂类型(map,list等) | 支持 | 不支持 |
松散语法:属性值多种形式展示:last-name,lastName,last_name(都表示lastName)
JsR303数据校验:
@Component
@ConfigurationProperties(prefix = "person")
@Data
@Validated
public class Person {
/**
* <bean class = "person">
* <property name= "lastName" value= "字面量/${key}从环境变量、配置文件中获取值/#{SpEl}"</property>
* </bean>
*/
// @Value("${person.last-name}"
//birth必须是邮箱格式
@Email
private String lastName;
运行测试:
配置文件yaml还是properties他们都能获取值;
如果说,我们只是在某个业务逻辑中徐娅萍获取一下配置文件中的某项值,使用@Value
如果说,我们专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties;
package com.atguigu.springboot.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Value("${person.last-name}")
String name;
@RequestMapping("/sayHello")
public String sayHello() {
return "Hello," + name;
}
}
重启spring后访问http://localhost:8080/sayHello