Spring组件配置文件主要分为两种:一种是主配置文件,另一种是其他配置文件。
在使用maven构建spring boot项目时会产生一个主要的配置文件application.properties
有些习惯yml的语法是
application.yml
都是一个意思,spring也能自动识别。
除了自动生成的配置文件外,其余的如file.properties
,redis.properties
都是新生成的spring无法自动识别需要通过spring相关配置类或注解引入配置文件。
Spring Boot启动时会自动加载默认配置文件的参数,但这些都是Spring Boot定义的,主配置文件中自定义的参数还是需要加载的。
加载主配置文件的自定义参数@ConfigurationProperties注解
SpringBoot默认会读取文件名为application.properties的资源文件,@ConfigurationProperties
注解以对象的形式加载文件的参数:
- 默认配置文件定义参数:
define.name = _xiaoxu_
define.sex = man
define.age = 18
- @ConfigurationProperties 注解加载到对象属性中
@Repository
@ConfigurationProperties(prefix = "define")
@Data
public class Define {
private String name;
private String age;
private String sex;
}
prefix
定义变量前缀,其后的内容需要与属性字段对应。
- 将对象DL注入IOC容器
- 装配对象和调用
@Autowired
private Define define;
@Test
void four(){
System.out.println("姓名:"+define.getName()+"年龄:"+define.getAge()+"性别:"+define.getSex());
}
如下图所示,调用成功:
@Value加载默认配置文件参数
还是之前的参数,这里使用@Value
注解
@Repository
@Data
public class DefineTwo {
@Value("${define.name}")
private String name;
@Value("${define.age}")
private String age;
@Value("${define.sex}")
private String sex;
}
@Value注解不需要引入文件,直接读取
application.properties
的属性,另外创建的类需要DL装配。
测试:
@Autowired
private DefineTwo defineTwo;
@Test
void five(){
System.out.println("姓名:"+define.getName()+"年龄:"+define.getAge()+"性别:"+define.getSex());
}
@PropertySource读取自定义配置文件
定义file.properties
文件
filepath=C:\\Users\\fireapproval\\Desktop\\数据集\\test.csv
redis直接在默认配置文件中进行配置,这里作为演示
//导入外部文件
@PropertySource("classpath:file.properties")
@Value("${filepath}")
private String filepath;
这里读取自定义文件后还面临一个重要的问题,就是@Value
注解,在类中使用赋值给属性,但是却并不是由spring 的IOC容器管理,这是需要生产对象返回该属性的值:
@Bean(name = "getFilePath")
//@Scope(value = "prototype")
public String getFilePath() throws UnsupportedEncodingException {
return new String(this.filepath.getBytes("ISO-8859-1"),"UTF-8");
}
如上是
@Bean
生产了一个对象获取了@Value
的属性,再返回具体的字符串,idea读取properties默认是IOS-8859-1。
bean生产出来后,可以通过@Autowired自动组装在其他地方使用:
//文件地址
@Autowired
private String getFilePath;
另外,我还遇到了自动装配属性的问题。场景如下:
- 在启动类导入文件中,首先注入属性,并在生产bean中注入返回属性的值。
- 自动装配其他类中的对象
//文件地址
@Autowired
private String getFilePath;
//获取全局的数据
ReadCSV readCSV = new ReadCSV();
List<ArrayList> maps = readCSV.readTwoColumn(getFilePath, 7, 9);
但这里后一致出现getFilePath
为null,这是由于对象生产和装配的时机不一样,导致bean还未生产
readTwoColumn
就在装配了,因此需要将装配方法通过函数包裹:
private List<ArrayList> getData(){
ReadCSV readCSV = new ReadCSV();
List<ArrayList> maps = readCSV.readTwoColumn(getFilePath, 7, 9);
return maps;
}
将生成的全局数据放在方法中,而不是直接放在类中。
spring引入外部属性或配置的注解还有:@Import
: 用来导入其他配置类。
@ImportResource
: 用来加载xml配置文件。