@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中的内容。

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值