@ConfigurationProperties 使用

@ConfigurationProperties 使用
背景,可以把屬性文件讀到bean裏方便使用。
【1】
pom.xml
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
【2】        
在application.properties同級位置建立fromp.properties文件,內容:
frompro.comp = "XIAN"
frompro.year = 2019    
【3】
建立對應於上面properties文件的實體FromProperity,內容如下
package com.example.demo.model;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:fromp.properties")  //指定properties文件位置。
@ConfigurationProperties(prefix = "frompro")
@Primary
public class FromProperity {
        String comp;
        int    year;
        public String getComp() {
            return comp;
        }
        public void setComp(String comp) {
            this.comp = comp;
        }
        public int getYear() {
            return year;
        }
        public void setYear(int year) {
            this.year = year;
        }
        
}
【4】在使用的地方,內容:

package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.example.demo.model.FromProperity;

@Component
//@EnableConfigurationProperties(FromProperity.class)
public class TestCommandLineRunner implements CommandLineRunner {

    @Autowired private FromProperity FP;// 注入實體 
    
    public void run(String... args) throws Exception {
         System.out.println("2019 run by CommandLineRunner ,COMP:"+FP.getComp()+",YEAR:"+FP.getYear());
    }

}

【5】輸出結果:
2019 run by CommandLineRunner ,COMP:"XIAN",YEAR:2019
2019-05-23 13:21:20.446  INFO 17416 --- [  restartedMain] .ConditionEvaluationDeltaLoggingListener : Condition evaluation unchanged

[備註]@ConfigurationProperties 找不到properties 文件,需要指定一下位置

    @PropertySource(只能用於properties文件)結合讀取指定文件

     @Value("${frompro.name}") 也可以讀到properties中的內容。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章