温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

配置文件如何利用SpringBoot 进行编写

发布时间:2020-11-25 13:49:52 来源:亿速云 阅读:131 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关配置文件如何利用SpringBoot 进行编写,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

在spirngBoot里面, 可以有两种方式声明配置

1、直接编写配置文件 然后从配置文件里面获取
2、编写配置文件 然后编写bean, 通过注解注入到bean里面 获取的时候从bean里面获取

配置文件编写可以有多种, 例如我们常见的有: xml、properties、json、yaml.....

我们这里就使用常见的properties文件来写

编写配置文件,从配置文件里面获取

创建配置文件

配置文件如何利用SpringBoot 进行编写

使用配置项

配置文件如何利用SpringBoot 进行编写

注解说明

@PropertySource({"classpath:config/web.properties"}) //指定配置文件

@Value("${site.name}") // 获取配置项 value

效果

配置文件如何利用SpringBoot 进行编写

编写配置文件, 从bean里面获取

编写bean, WebSetting.java

package com.example.demo.domain;

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

@Component
@PropertySource(value = "classpath:config/web.properties", encoding = "utf-8")
@ConfigurationProperties(prefix = "site") // 这个可以指定前缀 只要成员属性能对上就行 也可以不指定 使用@Value来获取
public class WebSetting {

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

  @Value("${site.desc}")
  private String siteDesc;

  @Value("${site.domain}")
  private String siteDomain;

  // 对上了可以不用@Value
  private String test;

  public String getTest() {
    return test;
  }

  public void setTest(String test) {
    this.test = test;
  }

  public String getSiteName() {
    return siteName;
  }

  public void setSiteName(String siteName) {
    this.siteName = siteName;
  }

  public String getSiteDesc() {
    return siteDesc;
  }

  public void setSiteDesc(String siteDesc) {
    this.siteDesc = siteDesc;
  }

  public String getSiteDomain() {
    return siteDomain;
  }

  public void setSiteDomain(String siteDomain) {
    this.siteDomain = siteDomain;
  }
}

config/web.properties

site.name=憧憬
site.domain=aoppp.com
site.desc=这是一个技术分享的博客!
site.test=test

获取配置 效果

配置文件如何利用SpringBoot 进行编写

需要注意点

1、配置文件注入失败,出现Could not resolve placeholder
   解决:根据springboot启动流程,会有自动扫描包没有扫描到相关注解,
   默认Spring框架实现会从声明@ComponentScan所在的类的package进行扫描,来自动注入,因此启动类最好放在根路径下面,或者指定扫描包范围,spring-boot扫描启动类对应的目录和子目录

2、注入bean的方式,属性名称和配置文件里面的key一一对应,就用加@Value 这个注解,如果不一样,就要加@value("${XXX}")

看完上述内容,你们对配置文件如何利用SpringBoot 进行编写有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI