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