首頁 > 軟體

springboot如何獲取yml裡面的屬性值

2022-02-16 10:04:59

如何獲取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;
    }
}

呼叫和方法一一樣的

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com