SpringBoot配置文件的读取

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 复选框。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值