欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浅谈springboot 属性定义

程序员文章站 2024-02-25 19:51:51
本文介绍了浅谈springboot 属性定义,分享给大家。具体如下: 简单属性自定义 一般属性可以定义在通用的配置文件application.properties里面...

本文介绍了浅谈springboot 属性定义,分享给大家。具体如下:

简单属性自定义

一般属性可以定义在通用的配置文件application.properties里面

# 自定义属性
boot.username = yuxi

如何获取呢?

按照spring的获取方式就可以了,很简单

 @value(value = "${boot.username}")
 private string username;

复杂属性自定义

在配置里配置属性

# 复杂属性
test.id=1
test.name=xiaoyuxixi
test.money=100000000

定义实体

//需要注意这个属性是必须的
@configurationproperties(prefix = "test")
public class account {
  private int id;
  private string name;
  private double money;

  public int getid() {
    return id;
  }

  public void setid(int id) {
    this.id = id;
  }

  public string getname() {
    return name;
  }

  public void setname(string name) {
    this.name = name;
  }

  public double getmoney() {
    return money;
  }

  public void setmoney(double money) {
    this.money = money;
  }

  @override
  public string tostring() {
    return "account{" +
        "id=" + id +
        ", name='" + name + '\'' +
        ", money=" + money +
        '}';
  }
}

注入属性

@restcontroller
// 这个属性也是必须的
@enableconfigurationproperties({account.class})
public class hellocontroller {
  //自定义属性
  @value(value = "${boot.username}")
  private string username;
  @autowired
  private account account;

  /**
   * 复杂 属性自定义
   *
   * @return
   */
  @requestmapping("/hard")
  public object gethardproperties() {

    return account;
  }

  /**
   * welcome spring boot
   *
   * @return
   */
  @requestmapping(value = "/", method = requestmethod.get)
  public string index() {
    return "greetings from spring boot! ";
  }

  /**
   * 简单 属性自定义
   *
   * @return
   */
  @requestmapping("/user")
  public string getproperties() {
    system.out.println(username);
    return username;
  }
  
}

在配置完复杂的属性之后,会发现这样写的话 application.properties里内容会很多有很多属性不是公共的配置,放在这里不是有优雅,可以把这些配置单独写一个配置文件

配置文件获取

添加配置文件 (test.properties)

# 配置文件获取
lakala.id=1
lakala.name=xiaoyuxixi
lakala.money=100000000

获取属性文件(在实体上加入以下配置文件)

@configuration
@propertysource(value = "classpath:test.properties")

源码地址:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。