1. 程式人生 > >springBoot 獲取配置檔案配置內容

springBoot 獲取配置檔案配置內容

配置檔案 src/main/resources 目錄下: book.properties

yuyi.book.name=三國演義
yuyi.book.count=100

一、使用@Value 註解注入屬性

package com.yuyi.bean.model;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 *  使用 @Value 註解注入屬性值 
 */
@Component
public class BookValue {
    
    @Value("${yuyi.book.name}")
    private String name;
    
    @Value("${yuyi.book.count}")
    private Integer count;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getCount() {
        return count;
    }
    public void setCount(Integer count) {
        this.count = count;
    }

}

二、使用 Environment 獲取配置資訊

package com.yuyi.bean.model;

import java.io.UnsupportedEncodingException;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * 使用 Environment 類獲取配置資訊
 */
@Component
public class BookEnvironment {
    
    @Autowired
    private Environment env;

    private String name;
    
    private Integer count; 
    
    @PostConstruct //註解標註該方法在構造器呼叫之後自動執行
    public void init() throws UnsupportedEncodingException{
        String strname = env.getProperty("yuyi.book.name");
        String strcount = env.getProperty("yuyi.book.count");
        
        name = strname;
        count = Integer.parseInt(strcount);
    }
 
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getCount() {
        return count;
    }
    public void setCount(Integer count) {
        this.count = count;
    }
    
}

三、使用  @ConfigurationProperties 註解注入配置資訊

package com.yuyi.bean.model;

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

/**
 * 使用 @ConfigurationProperties注入配置資訊
 */
@Component
@ConfigurationProperties(prefix = "yuyi.book")
@PropertySource(value = "classpath:book.properties", encoding = "UTF-8")  //配置檔案位置, 編碼方式
public class BookProperties {
    
    private String name;
    
    private Integer count;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public Integer getCount() {
        return count;
    }
    public void setCount(Integer count) {
        this.count = count;
    }
 
}