springboot_读取自定义配置的两种方式

一、核心配置文件

核心配置文件是指在resources根目录下的application.properties或application.yml配置文件。

我们写自定义配置也一般写在这个文件里,但实际上我们为了方便区分和管理,我们可以自己新建一个properties文件,需要注意的是,如果你application.properties或application.yml里也写上了相同的配置,springboot会优先读取application.properties或application.yml里的配置。

二、读取自定义配置文件

这里我在resource目录下新建了一个school.properties

school.name=加里敦大学
school.address=阿拉斯加
school.age=100

读取方式一:在相应变量上加@value注解

package com.rong.controller;

import com.rong.config.ConfigInfo;
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 ConfigInfoController {

    /**
     * 读取自定义配置的方式一
     */

    @Value("${school.name}")
    private String name;

    @Value("${school.address}")
    private String address;

    @Value("${school.age}")
    private int age;

    @GetMapping("/inits")
    private String initConfigInfo1(){
        return name + " " + address + " " + age;
    }
}

这里访问localhost:8080/inits就会得到加里敦大学  阿拉斯加  100了

读取方式二:

需要先写个配置类

package com.rong.config;

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

/**
 * 作为配置类
 */
@Component//会将该类的对象加入到容器中
@PropertySource(value = "classpath:myschool.properties")//指定外部配置文件的名字
@ConfigurationProperties(prefix = "school")//表示会从配置文件中读取以school开头的内容
public class ConfigInfo {

    private String name;

    private String address;

    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

之后再controller里使用@Autowired自动注入

package com.rong.controller;

import com.rong.config.ConfigInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConfigInfoController {

    /**
     * 读取自定义配置的方式二
     */
    @Autowired
    private ConfigInfo configInfo;

    @GetMapping("/init")
    public String initConfigInfo2() {
        return configInfo.getName();
    }
}

这里我只返回的是name,即访问localhost:8080/init就可以得到  ”加里敦大学“了

发布了60 篇原创文章 · 获赞 10 · 访问量 9182

猜你喜欢

转载自blog.csdn.net/chaseqrr/article/details/104393994