SpringBoot配置文件
springboot的配置文件主要有两种,properties和yaml
使用properties配置:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
jyu.name=zhangsan
jyu.test=李四
使用yaml配置
jyu:
name: zhangsan
test: 李四
读取单个配置项,使用@Value注解:
@Value("${jyu.name}")
String name;
读取多个配置,使用@ConfifigurationProperties
@Component
@ConfigurationProperties(prefix = "jyu")
public class User {
String name;
String test;
//getter and setter。。。
}
以 jyu开头的属性会⾃动赋值到对象的属性中,⽐如,jyu.name 会⾃动赋值到name中
测试:
@SpringBootTest
public class UserTest {
@Autowired
public User user;
@Value("${jyu.name}")
String name;
@Test
public void test01() {
if (user == null) {
System.out.println("null");
return;
}
System.out.println(user.name);
System.out.println(user.test);
System.out.println(name);
}
}
自定义配置,使用@PropertySource
@Component
@ConfigurationProperties(prefix="other")
@PropertySource("classpath:other.properties")
public class OtherProperties {
private String title;
private String blog;
}
IDEA配置文件中文乱码问题:
依次单击 File | Settings | Editor | File Encodings 命令,将 Properties Files (*.properties) 下的 Default
encoding for properties fifiles 设置为 UTF-8,勾选 Transparent native-to-ascii conversion 复选框。