springboot入门(二):关于springboot文件的yml配置文件配置

本文详细介绍SpringBoot项目中配置文件的使用与属性注入的方法,包括如何通过application.yml进行配置,以及如何在Java代码中使用@Value和@ConfigurationProperties注解来获取配置文件中的属性。
  1. 关于创建springboot项目之前已经说过了,本文将通过hello的项目原型讲解。
    创建springboot项目

  2. 在resources的文件目录下创建application.yml,一般配置文件一个就可以了,将application.properties删除。

    application.yml的代码,一定注意值和属性之间有:和空格。

helloWorld: "Hello World"

HelloController.java的代码。

package com.luffykaiyuan.hello.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Value("${helloWorld}")
    private String hello;

    @GetMapping("/hello")
    public String say(){
        return hello;
    }
}

使用@Value获取配置文件中的值。

  1. 获取多个值的配置
    当需要获取的值多了,不可以一大串@Value注解,显得冗余。
    我们可以将配置的属性看成一个对象的属性。
    yml文件配置
limit:
  hello: "newHello"
  world: "newWorld"

新建一个对象HelloWorld.java。

package com.luffykaiyuan.hello;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "limit")
public class HelloWorld {

    private String hello;

    private String world;

    public void setHello(String hello) {
        this.hello = hello;
    }

    public void setWorld(String world) {
        this.world = world;
    }

    public String getHello() {
        return hello;
    }

    public String getWorld() {
        return world;
    }
}

通过ConfigurationProperties注解获取文件,prefix 获取前缀,当有多个前缀时用.分割。
注意属性名必须和yml中的对应。

最后controller中

package com.luffykaiyuan.hello.controller;

import com.luffykaiyuan.hello.HelloWorld;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Autowired
    private HelloWorld hello;

    @GetMapping("/hello")
    public String say(){
        return hello.getHello() + "-----" + hello.getWorld();
    }
}

启动运行结果。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值