SpringBoot学习笔记(上)

张宇杰 2023-04-24 12:12:23

SpringBoot 配置

小结
SpringBoot提供了2种配置文件类型: properteis和yml / yaml
默认配置文件名称:application
同一级目录下优先级为: properties>yml>yaml

 

YAML小结


 配置文件类型
(1)properties:和以前一样
         yml/yaml:注意空格

(2) yaml: 简洁,以数据为核心

  •   基本语法
  1.   大小写敏感
  2.   数据值前边必须有空格,作为分隔符
  3.   使用空格缩进表示层级关系,相同缩进表示同一级
  • 数据格式
  1. 对象
  2. 数组:使用“_”表示数组每个元素
  3. 纯量
  •   参数引用

         $ikey)

server:
  port: 8083

  name: abc
#  对象
person:
  name: ${name}
  age: 20

#  行内对象写法
person2: {name: scc, age: 20}

#数组
address:
  - xian
  - beijing
#  行内数组写法
address2: [xian,beijing]

#  纯量
msg1: 'hello \n world'
msg2: "hello \n world"

读取配置内容

 

  • @Value
  • Environment
  •  @ConfigurationProperties
  • (1)
    @Value("${name}")
    private String name;
    
    @Value("${person.name}")
    private String name2;
    
    @Value("${person.age}")
    private int age;
    
    @Value("${address[0]}")
    private String address1;
    
    @Value("${msg1}")
    private String msg1;
    
    @Value("${msg2}")
    private String msg2;
    
    (2)
    @Autowired
    private Environment env;
    System.out.println(env.getProperty("address[1]"));
    
    (3)
    @ConfigurationProperties(prefix = "person")

    ps:

    Test文件无法使用runwith注解的解决方法 

    引入下面依赖

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-test</artifactId>

        <scope>test</scope>

    </dependency>

    <dependency>

         <groupId>junit</groupId>

         <artifactId>junit</artifactId>

         <version>4.13</version>

     </dependency>

  • /**
     *
     * 测试类
     *
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = SpringbootTestApplication.class)
    public class UserServiceTest {
    
        @Autowired
        private UserService userService;
    
        @Test
        public void testADdd(){
            userService.add();
        }
    }

     

...全文
98 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

50

社区成员

发帖
与我相关
我的任务
社区描述
产学研究,学术传承
社区管理员
  • 又菜又爱玩呜呜呜~
  • 两年半的个人练习生^_^
  • yolanda19910002
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧