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配置文件。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/156181.html