@PropertySrource读取其他properties配置文件

需要掌握:使用@ConfigurationProperties读取application.properties和application.yml

介绍

@PropertySrource注解用于读取其他xxx.properties配置文件

只能用于xxx.properties

创建配置文件

在springboot工程的resources文件夹下创建db.properties配置文件,内容如下:

db.url=127.0.0.1:7788
db.name=root
db.pwd=12345678

创建bean

使用 @PropertySrource注解指定要读取的配置文件

package top.malaoshi.bean;

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

@Component
@PropertySource(value={"classpath:db.properties"})
@ConfigurationProperties(prefix = "db")
public class DbProperties {
    private String url;
    private String name;
    private String pwd;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getName() {
        return name;
    }

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

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}

使用

package top.malaoshi.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import top.malaoshi.bean.DbProperties;

@RestController
public class DbController {

    @Autowired
    private DbProperties db;

    @GetMapping("/db")
    public String db(){
        return String.format("url:%s--name:%s--pwd:%s", db.getUrl(),db.getName(),db.getPwd());
    }

原文出处:/show_1EF5rAX9qrHb.html