欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Springboot引入多个yml方法(多种方案)

时间:2021-01-27 10:38:32|栏目:JAVA代码|点击:

SpringBoot默认加载的是application.yml文件,所以想要引入其他配置的yml文件,就要在application.yml中激活该文件

定义一个application-resources.yml文件(注意:必须以application-开头)

application.yml中:

 spring:
  profiles:
    active: resources

以上操作,xml自定义文件加载完成,接下来进行注入。

application-resources.yml配置文件代码:

user:
 filepath: 12346
 uname: "13"

admin:
 aname: 26

方案一:无前缀,使用@Value注解

@Component
//@ConfigurationProperties(prefix = "user")
public class User {
  @Value("${user.filepath}")
  private String filepath;
  @Value("${user.uname}")
  private String uname;
  public String getFilepath() {
    return filepath;
  }
  public void setFilepath(String filepath) {
    this.filepath = filepath;
  }
  public String getUname() {
    return uname;
  }
  public void setUname(String uname) {
    this.uname = uname;
  }
  @Override
  public String toString() {
    return "User{" +
        "filepath='" + filepath + '\'' +
        ", uname='" + uname + '\'' +
        '}';
  }
}

方案二:有前缀,无需@Value注解

@Component
@ConfigurationProperties(prefix = "user")
public class User {
  //@Value("${user.filepath}")
  private String filepath;
  //@Value("${user.uname}")
  private String uname;
  public String getFilepath() {
    return filepath;
  }
  public void setFilepath(String filepath) {
    this.filepath = filepath;
  }
  public String getUname() {
    return uname;
  }
  public void setUname(String uname) {
    this.uname = uname;
  }
  @Override
  public String toString() {
    return "User{" +
        "filepath='" + filepath + '\'' +
        ", uname='" + uname + '\'' +
        '}';
  }
}


测试类:

package com.sun123.springboot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UTest {
  @Autowired
  User user;
  @Test
  public void test01(){
    System.out.println(user);
  }
}

测试结果:

总结

上一篇:Java多线程用法的实例详解

栏    目:JAVA代码

下一篇:实例分析Java Class的文件结构

本文标题:Springboot引入多个yml方法(多种方案)

本文地址:http://www.codeinn.net/misctech/51954.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有