Spring中@Value注解使用——一種新的直接讀取配置文件的方式


1.@Value注解作用

該注解的作用是將我們配置文件的屬性讀出來,有@Value(“${}”)和@Value(“#{}”)兩種方式。

2.@Value注解作用的兩種方式

場景

假如有以下屬性文件dev.properties, 需要注入下面的tager

第一種方式@Value(“${}”):

server.port=8000

通過PropertyPlaceholderConfigurer

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="dev.properties" />
</bean>

代碼

@Value("${server.port}")
private String tag;

項目一旦運行,private String tag屬性的值就會被賦值為8000

第二種方式 @Value(“#{}”):

通過PreferencesPlaceholderConfigurer

<bean id="appConfig" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
    <property name="location" value="dev.properties" />
</bean>

代碼:

@Value("#{config['server.port']}") private String tag;

項目一旦運行,private String tag屬性的值也會被賦值為8000

2.@Value注解作用的其他方式

(1)常量注入

    @Value("normal")

    private String normal; // 注入普通字符串

    @Value("classpath:com/hry/spring/configinject/config.txt")

    private Resource resourceFile; // 注入文件資源

    @Value("http://www.baidu.com")

    private Resource testUrl; // 注入URL資源

 

參考網址:https://www.cnblogs.com/rain-in-summer/p/7382003.html

     https://blog.csdn.net/woheniccc/article/details/79804600

       https://www.cnblogs.com/bclshuai/p/10309119.html

 

 

 

 

 

 

 

 
        


免責聲明!

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



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