springboot 属性定义 浅谈springboot 属性定义

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

springboot 属性定义 浅谈springboot 属性定义

小鱼嘻嘻   2021-03-29 我要评论
想了解浅谈springboot 属性定义的相关内容吗,小鱼嘻嘻在本文为您仔细讲解springboot 属性定义的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:springboot,属性定义,springboot,属性,下面大家一起来学习吧。

本文介绍了浅谈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")

源码地址:springbootlearning_jb51.rar

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们