springboot-day6-获取配置文件中的参数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011066470/article/details/88379077

一 .配置文件的说明

YAML(Yet Another Markup Language)
  写 YAML 要比写 XML 快得多(无需关注标签或引号)
  使用空格 Space 缩进表示分层,不同层次之间的缩进可以使用不同的空格数目
 注意:key后面的冒号,后面一定要跟一个空格,树状结构

二.获取配置文件中的参数

方法1:

1、Controller上面配置
    
           @PropertySource({"classpath:application.properties"})
            2、增加属性
                 @Value("${image.upload-path}")
                  private String uploadPath;

配置文件application:

image: 
  upload-path: /Users/jack/Desktop

controller层:

页面访问:

方法二:通过封装javabean,调用使用

1.application配置文件

name: liu

2.获取参数bean

package com.ljf.springboot.helloworld.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value="classpath:application.yml")
@ConfigurationProperties
public class ParamterUtil {
    @Value("${name}")
    private String myName;

    public String getMyName() {
        return myName;
    }

    public void setMyName(String myName) {
        this.myName = myName;
    }
}

3.引用:必须 通过注入IOC对象Resource 进来 , 才能在类中使用获取的配置文件值

public class UserController {
    @Autowired
    private ParamterUtil pu;
    @GetMapping("/api/user")
    public String getUser(){

        return "my name is ljf!"+pu.getMyName();
    }
}

4.页面访问:

5.说明:配置参数多层级,可以使用前缀

如配置文件:

test:
  name: liujian

javabean中使用前缀注解,当配置文件的属性名和javabean属性名一致时候,可以省略@value注解

package com.ljf.springboot.helloworld.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value="classpath:application.yml")
//@ConfigurationProperties
@ConfigurationProperties(prefix="test")
public class ParamterUtil {
    @Value("${name}")
    private String myName;

    public String getMyName() {
        return myName;
    }

    public void setMyName(String myName) {
        this.myName = myName;
    }
}

3.引用:必须 通过注入IOC对象Resource 进来 , 才能在类中使用获取的配置文件值

public class UserController {
    @Autowired
    private ParamterUtil pu;
    @GetMapping("/api/user")
    public String getUser(){

        return "my name is ljf!"+pu.getMyName();
    }
}

结果:

注入bean的方式,属性名称和配置文件里面的key一一对应,就用加@Value 这个注解,  如果不一样,就要加@value("${XXX}")

猜你喜欢

转载自blog.csdn.net/u011066470/article/details/88379077