为了简化读取properties文件中的配置值,spring支持@value注解的方式来获取,这种方式大大简化了项目配置,提高业务中的灵活性。
-
两种使用方法
1)@Value("#{configProperties['key']}")
2)@Value("${key}")
-
配置文件示例
ftp:
ftplp: 10.2.23.89
ftpPort: 21
ftpUser: uftp
ftpPwd: 12345678
ftpRemotePath: /home
说明:以上是配置文件中的信息,主要是一些账号密码等信息。
- 读取yml配置文件的工具类
package com.dbright.dataprediction.entity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:ftpconfig.yml")
@ConfigurationProperties(prefix = "ftp")
public class FtpProperties {
@Value("${ftplp}")
public String ftplp;
@Value("${ftpPort}")
public String ftpPort;
@Value("${ftpUser}")
public String ftpUser;
@Value("${ftpPwd}")
public String ftpPwd;
@Value("${ftpRemotePath}")
public String ftpRemotePath;
public String getFtplp() {
return ftplp;
}
public void setFtplp(String ftplp) {
this.ftplp = ftplp;
}
public String getFtpPort() {
return ftpPort;
}
public void setFtpPort(String ftpPort) {
this.ftpPort = ftpPort;
}
public String getFtpUser() {
return ftpUser;
}
public void setFtpUser(String ftpUser) {
this.ftpUser = ftpUser;
}
public String getFtpPwd() {
return ftpPwd;
}
public void setFtpPwd(String ftpPwd) {
this.ftpPwd = ftpPwd;
}
public String getFtpRemotePath() {
return ftpRemotePath;
}
public void setFtpRemotePath(String ftpRemotePath) {
this.ftpRemotePath = ftpRemotePath;
}
}
说明:以上是使用@value注解来读取yml配置文件的代码示例
1)@component —— 把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>
- @PropertySource("classpath:ftpconfig.yml") ——
设置yml文件的路径,方便扫描到。一般我们配置文件都是放在resources包下。所以我们只需要 classpath+所需要读取的配置文件名称。
3)@ConfigurationProperties(prefix = "ftp") —— 这个不需要解释太多,配置文件里面内容的前缀,我们读取的是ftp下的信息。
4)@Value("${ftplp}") —— 这是读取我们所需的配置信息,美元符号+{字段名}即可制定
5)下面定义字符串来接收所读取到的配置信息。
6)写set和get方法,方便外部类调用。
- 演示:效果图如下 可以看到,我们成功取到了我们想要的值。
- 一开始说的第二种和这个差不多,把{}外的 $ 变成 # 号,然后里面指定配置文件的信息+字段而已。大同小异,我就不贴代码上来了。
今天的内容就到这里啦,谢谢观看!
有需要源码的,或者有不理解,欢迎关注微信公众号(全员格子)来讨论,留言会回复的哦~
赞赏码