@value注解的使用,yml文件和properties文件的注意事项

SpringBoot使用注意事项

@Value为属性赋值

msg:
	hello:"hello"
msg.hello=hello word

Controller

@RestController
@RequestMapping("hello")
public class HelloController {
    @Value("${msg.hello}")
    private String msg;
    @GetMapping("doGetMsg")
    public String doGetMsg(){
        return msg;
    }
}

1.2properties文件为属性赋值

业务有时会需要动态赋值,如果将大量的业务数据写到yml文件中,导致代码混乱,最好指定properties文件为业务赋值

1.2.1编辑properties文件

#语法:
#数据结构:   key=value
#注意事项:   不要添加""号 本身就是字符串.
#字符集编码:  写法采用utf-8,程序读取时采用ISO-8859-1
pro.msg=配置信息

1.2.2动态赋值

在这里插入图片描述

controller层

@RestController
@RequestMapping("hello")
@PropertySource(value= "classpath:/properties/msg.properties",encoding = "UTF-8")
public class HelloController {
    @Value("${msg.hello}")
    private String msg;
    @GetMapping("doGetMsg")
    public String doGetMsg(){
        System.out.println(msg);
        return msg;
    }
}

在这里插入图片描述

2.1环境切换

要求: 不管是几个环境,要求配置项都必须相同,值可以不同
语法:
1.使用—实现YML配置文件的分割
2.定义环境名称
3.定义默认环境名称

#指定默认的环境
spring:
  profiles:
    active: test
---

#关于YML配置文件说明
# 1.数据结构    key=value
# 2.数据类型    默认都是字符串 如果需要类型转化,则框架已经在内部完成
# 3.yml写法:   1.key: (空格)value  2.有层级结构 编辑时注意
# 4.字符集编码: 默认程序加载时都是UTF-8
#定义环境名称
spring:
  config:
    activate:
      on-profile: dev

server:
  port: 8080
  #项目发布的路径
  servlet:
    #  /缺省值  localhost:8080/jt/xxxx请求路径
    context-path: /

#2.为属性赋值  hello代表前缀    key=hello.msg
hello:
    msg: "我喜欢开发"

#环境分割线
---
spring:
  config:
    activate:
      on-profile: test

server:
  port: 8090
  #项目发布的路径
  servlet:
    #  /缺省值  localhost:8080/jt/xxxx请求路径
    context-path: /

#2.为属性赋值  hello代表前缀    key=hello.msg
hello:
  msg: "我喜欢测试"
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值