Spring MVC 經過 @PropertySource和@Value 來讀取配置文件

在這篇文章中,咱們會利用Spring的@PropertySource和@Value兩個註解從配置文件properties中讀取值。先來段java代碼:java

@Component
@PropertySource(value = {"classpath:common.properties", "classpath:abc.properties"})
public class Configs {

    @Value("${connect.api.apiKeyId}")
    public String apiKeyId;

    @Value("${connect.api.secretApiKey}")
    public String secretApiKey;

    public String getApiKeyId() {
        return apiKeyId;
    }

    public String getSecretApiKey() {
        return secretApiKey;
    }
}

咱們來具體分析下:api

一、@Component註解說明這是一個普通的bean,在Component Scanning時會被掃描到並被注入到Bean容器中;咱們能夠在其它引用此類的地方進行自動裝配。@Autowired這個註解表示對這個bean進行自動裝配。 好比:spa

@Controller
public class HomeController {

    @Autowired
    private Configs configs;
}

二、@PropertySource註解用來指定要讀取的配置文件的路徑從而讀取這些配置文件,能夠同時指定多個配置文件;code

三、@Value("${connect.api.apiKeyId}")用來讀取屬性key=connect.api.apiKeyId所對應的值並把值賦值給屬性apiKeyId;blog

四、經過提供的get方法來獲取屬性值,如:ip

@Controller
public class HomeController {

    @Autowired
    private Configs configs;
    
    private void decrytCardInfo(AtomRequest req) throws Exception {
        req.setCardNo(ChipherUtils.desDecrypt(ChipherUtils.decodeBase64(req.getCardNo()), configs.getCardKey(), Consts.CHARSET_UTF8));
    }
}

總結:get

@Component+@PropertySource+@Value==強大+便捷+高效io

相關文章
相關標籤/搜索