SpringBoot自定義屬性配置以及@ConfigurationProperties注解與@Value注解區別


我們可以在application.properties中配置自定義的屬性值,為了獲取這些值,我們可以使用spring提供的@value注解,還可以使用springboot提供的@ConfigurationProperties注解非常方便的完成屬性值的注入。

1. 在application.properties中添加自定義屬性配置

#七牛oss配置
qiniu.accessKey = zcqSW4uul68vm7K_ryHEYPVTpM-9H7UP0eslY3xk
qiniu.secretKey = 2QwaKSktWm5O1sIaqQqzqOMF6WtD6sncNnRaYB4w
qiniu.bucket = blog
qiniu.path = http://static.wangkaihua.com

2. 編寫Bean類,加載屬性

Sam類需要添加@Component注解,讓spring在啟動的時候掃描到該類,並添加到spring容器中。

第一種:使用spring支持的@Value()實現

import org.springframework.stereotype.Component;

/**
 * 七牛oss 文件上傳的相關配置類
 * @author wangkaihua
 */

@Component
public class QiNiuConfig {
    @Value("${qiniu.accessKey}")
    private String accessKey;
    
    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.path}")
    private String path;
    //省略getXXX、setXXX方法
}

第二種:使用@ConfigurationProperties(prefix="") 設置前綴,屬性上不需要添加注解。

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 七牛oss 文件上傳的相關配置類
 * @author wangkaihua
 */
@Component
@ConfigurationProperties(prefix = "qiniu")
public class QiNiuConfig {
    private String accessKey;
    private String secretKey;
    private String bucket;
    private String path;
    //省略getXXX、setXXX方法
}

3. 在controller中或者service中注入並使用QiNiuConfig這個Bean。

@Component
public class QiniuUtil {
    @Autowired
    private QiNiuConfig qiNiuConfig;
 
    public String uploadImg(FileInputStream file) throws QiniuException {
	// 省略xxxxxx
        System.out.printl("獲取自定義屬性值:"+qiNiuConfig.getPath());
        System.out.printl("獲取自定義屬性值:"+qiNiuConfig.getBucket());
    }
}

區別

  • @ConfigurationProperties能夠批量注入配置文件的屬性。@Value只能一個個指定。
  • @ConfigurationProperties支持松散綁定。@ConfigurationProperties(prefix = "person"),只需要指定一個前綴,就能綁定有這個前綴的所有屬性值。
  • @Value支持SpringEl的語法。@ConfigurationProperties不支持SpringEl的語法。
  • @ConfigurationProperties還支持JSR303進行配置文件值及校驗。
@Component
@ConfigurationProperties(prefix = "qiniu")
@Validated
public class QiNiuConfig {
    @NotNull
    private String accessKey;
    @NotNull
    private String secretKey;
    @NotNull
    private String bucket;
    @Email
    private String path;
    //省略getXXX、setXXX方法
}

當我們注入的不是一個郵箱格式時,啟動項目報錯:

***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target com.wangkaihua.myblog.common.QiNiuConfig@3e792ce3 failed:
    Property: qiniu.path
    Value: http://static.wangkaihua.com
    Reason: 不是一個合法的電子郵件地址
Action:
Update your application's configuration

總結

如果說,我們只是在某個業務邏輯中需要獲取一下配置文件中的某項值,使用@Value,如果我們要編寫了一個javabean和配置文件進行映射,就直接使用ConfigurationProperties簡化配置;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM