springboot如何获取yml里面的属性值

 更新时间:2022年02月16日 08:51:25   作者:别浪呀  
这篇文章主要介绍了springboot如何获取yml里面的属性值,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

如何获取yml里面的属性值

开发环境

  • idea
  • jdk1.8

项目结构

pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.springboot</groupId>
    <artifactId>springboot_demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_demo</name>
    <description>Demo project for Spring Boot</description>
 
    <properties>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--导入配置文件处理器,配置文件绑定数据会有数据-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build> 
</project>

springboot启动类

package com.springboot.springboot_demo; 
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
 
@SpringBootApplication
public class SpringbootDemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(SpringbootDemoApplication.class, args);
    }
    /**
     * 设置自定义yml位置
     *
     * @return
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(
                new ClassPathResource[] {
                        /** 请求url地址 */
                        new ClassPathResource("config/person.yml")
                });
        pspc.setProperties(yaml.getObject());
        return pspc;
    }
}

person.yml

person:
  lastName: zhangsan
  age: 18
  boss: false
  birth: 2017/12/12
  maps: {k1: v1,k2: v2}
  lists:
    - lisi
    - zhaoliu
  dog:
    name: 小狗
    age: 2

person.java

package com.springboot.springboot_demo.pojo; 
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; 
import java.util.Date;
import java.util.List;
import java.util.Map;
 
/**
 * 将配置文件中配置的每一个属性的值映射到person
 * @ConfigurationProperties 告诉springboot 将本类中的值与配置文件中的值绑定
 * prefix = "person" 配置文件下的那个属性下的
 * 只有这个组件是容器中的组件才能使用@Component
 */
@Data
@Component
@ConfigurationProperties(prefix = "person")
public class Person { 
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog; 
}

Dog.java

package com.springboot.springboot_demo.pojo; 
import lombok.Data; 
@Data
public class Dog {
    private String name;
    private String age;
 
}

SpringbootDemoApplicationTests

package com.springboot.springboot_demo; 
import com.springboot.springboot_demo.pojo.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
/**
 * springboot单元测试
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootDemoApplicationTests { 
    @Autowired
    private Person person;
    @Value("${person.lastName}")
    private String username;
    @Test
    public void contextLoads() {
        System.out.println(person);
    }
    @Test
    public void personCopy() {
        System.out.println(username);
    } 
}

控制台输出

Person(lastName=zhangsan, age=18, boss=false, birth=Tue Dec 12 00:00:00 CST 2017, maps={k1=v1, k2=v2}, lists=[lisi, zhaoliu], dog=Dog(name=小狗, age=2))

zhangsan

获取.yml中自定义参数

需求:根据不同环境获取到不同的参数,放在.yml中方便修改!

在开发环境中,回调的url地址

在测试环境中,回调的url地址

在生产环境中,回调的url地址

我是通过2种方式来实现的

通过@Value获取

代码如下

package com.heque.service.pay;
import org.springframework.beans.factory.annotation.Value;
public abstract class ObtainNotifyUrl {
    @Value("${weixinAndAli.wechatNotifyUrl}")
    private String wechatNotifyUrl;
    @Value("${weixinAndAli.aliNotifyUrl}")
    private String aliNotifyUrl;
    public String getWechatNotifyUrl() {
        return wechatNotifyUrl;
    }
    public void setWechatNotifyUrl(String wechatNotifyUrl) {
        this.wechatNotifyUrl = wechatNotifyUrl;
    }
    public String getAliNotifyUrl() {
        return aliNotifyUrl;
    }
    public void setAliNotifyUrl(String aliNotifyUrl) {
        this.aliNotifyUrl = aliNotifyUrl;
    }
}
package com.heque.service.pay;
import org.springframework.stereotype.Component;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
@Component
public class Test extends ObtainNotifyUrl{    
}

通过springframework自动包可以完成此功能,需要注意Test继承对象需要加入@component,把对象交给springContainer去管理,我们需要的时候只需注入资源就好了。

@Autowired private Test test; test.getAliNotifyUrl();/test.getWechatNotifyUrl();

通过@ConfigurationProperties(prefix = "weixinAndAli")注解

代码如下

package com.heque.service.pay;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
 * @author: TimBrian
 * @date: Sep 10, 2018 9:13:40 AM      
 */
@Component
@ConfigurationProperties(prefix = "weixinAndAli")
public class ConfigUtils {    
    private String wechatNotifyUrl;    
    private String aliNotifyUrl;    
    public String getWechatNotifyUrl() {
        return this.wechatNotifyUrl;
    }
    public void setWechatNotifyUrl(String wechatNotifyUrl) {
        this.wechatNotifyUrl = wechatNotifyUrl;
    }
    public String getAliNotifyUrl() {
        return aliNotifyUrl;
    }
    public void setAliNotifyUrl(String aliNotifyUrl) {
        this.aliNotifyUrl = aliNotifyUrl;
    }
}

调用和方法一一样的

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java正则判断日期格式是否正确的方法示例

    Java正则判断日期格式是否正确的方法示例

    这篇文章主要介绍了Java正则判断日期格式是否正确的方法,结合实例形式分析了Java针对日期字符串正则判断的相关操作技巧,需要的朋友可以参考下
    2017-03-03
  • 解决SpringBoot返回结果如果为null或空值不显示处理问题

    解决SpringBoot返回结果如果为null或空值不显示处理问题

    这篇文章主要介绍了解决SpringBoot返回结果如果为null或空值不显示处理问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • 一文了解mybatis的延迟加载

    一文了解mybatis的延迟加载

    本文主要为大家详细介绍下mybatis的延迟加载,从原理上介绍下怎么使用、有什么好处能规避什么问题。感兴趣的小伙伴可以跟随小编一起学习一下
    2022-07-07
  • Java8新日期时间API的20个使用示例

    Java8新日期时间API的20个使用示例

    这篇文章主要介绍了Java8新日期时间API的20个使用示例,为了学习Java 8的这个新库,这里我创建了20个以任务为导向的例子,需要的朋友可以参考下
    2015-03-03
  • JVM Metaspace内存溢出问题解决方案

    JVM Metaspace内存溢出问题解决方案

    这篇文章主要介绍了JVM Metaspace内存溢出排查总结过程图解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • jdbc实现连接和增删改查功能

    jdbc实现连接和增删改查功能

    这篇文章主要为大家详细介绍了jdbc实现连接和基本的增删改查功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-02-02
  • java 抓取网页内容实现代码

    java 抓取网页内容实现代码

    这篇文章主要介绍了java 抓取网页内容实现代码,需要的朋友可以参考下
    2014-02-02
  • SpringBoot项目启动时提示程序包不存在和找不到符号的处理方法

    SpringBoot项目启动时提示程序包不存在和找不到符号的处理方法

    最近接手同事开发的一个Springboot工作项目,从svn上整体拉取下来后,构建完成后,启动的时候遇到了程序包找不到的情况,所以本文记录了SpringBoot项目启动时提示程序包不存在和找不到符号的处理方法,需要的朋友可以参考下
    2024-05-05
  • 关于spring boot使用 jdbc+mysql 连接的问题

    关于spring boot使用 jdbc+mysql 连接的问题

    这篇文章主要介绍了spring boot使用 jdbc+mysql 连接,在这里mysql 8.x版本驱动包,要使用 com.mysql.cj.jdbc.Driver作为驱动类,文中给大家详细介绍,需要的朋友可以参考下
    2022-03-03
  • Java ServletContext与ServletConfig接口使用教程

    Java ServletContext与ServletConfig接口使用教程

    ServletConfig对象,叫Servlet配置对象。主要用于加载配置文件的初始化参数。我们知道一个Web应用里面可以有多个servlet,如果现在有一份数据需要传给所有的servlet使用,那么我们就可以使用ServletContext对象了
    2022-09-09

最新评论